2
0

detect.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. import methods
  2. import os
  3. def is_active():
  4. return True
  5. def get_name():
  6. return "Windows"
  7. def can_build():
  8. if (os.name == "nt"):
  9. # Building natively on Windows
  10. # If VCINSTALLDIR is set in the OS environ, use traditional Godot logic to set up MSVC
  11. if (os.getenv("VCINSTALLDIR")): # MSVC, manual setup
  12. return True
  13. # Otherwise, let SCons find MSVC if installed, or else Mingw.
  14. # Since we're just returning True here, if there's no compiler
  15. # installed, we'll get errors when it tries to build with the
  16. # null compiler.
  17. return True
  18. if (os.name == "posix"):
  19. # Cross-compiling with MinGW-w64 (old MinGW32 is not supported)
  20. mingw32 = "i686-w64-mingw32-"
  21. mingw64 = "x86_64-w64-mingw32-"
  22. if (os.getenv("MINGW32_PREFIX")):
  23. mingw32 = os.getenv("MINGW32_PREFIX")
  24. if (os.getenv("MINGW64_PREFIX")):
  25. mingw64 = os.getenv("MINGW64_PREFIX")
  26. test = "gcc --version > /dev/null 2>&1"
  27. if (os.system(mingw64 + test) == 0 or os.system(mingw32 + test) == 0):
  28. return True
  29. return False
  30. def get_opts():
  31. from SCons.Variables import BoolVariable, EnumVariable
  32. mingw32 = ""
  33. mingw64 = ""
  34. if (os.name == "posix"):
  35. mingw32 = "i686-w64-mingw32-"
  36. mingw64 = "x86_64-w64-mingw32-"
  37. if (os.getenv("MINGW32_PREFIX")):
  38. mingw32 = os.getenv("MINGW32_PREFIX")
  39. if (os.getenv("MINGW64_PREFIX")):
  40. mingw64 = os.getenv("MINGW64_PREFIX")
  41. return [
  42. ('mingw_prefix_32', 'MinGW prefix (Win32)', mingw32),
  43. ('mingw_prefix_64', 'MinGW prefix (Win64)', mingw64),
  44. # Targeted Windows version: 7 (and later), minimum supported version
  45. # XP support dropped after EOL due to missing API for IPv6 and other issues
  46. # Vista support dropped after EOL due to GH-10243
  47. ('target_win_version', 'Targeted Windows version, >= 0x0601 (Windows 7)', '0x0601'),
  48. EnumVariable('debug_symbols', 'Add debugging symbols to release builds', 'yes', ('yes', 'no', 'full')),
  49. BoolVariable('separate_debug_symbols', 'Create a separate file containing debugging symbols', False),
  50. ('msvc_version', 'MSVC version to use. Ignored if VCINSTALLDIR is set in shell env.', None),
  51. BoolVariable('use_mingw', 'Use the Mingw compiler, even if MSVC is installed. Only used on Windows.', False),
  52. BoolVariable('use_llvm', 'Use the LLVM compiler', False),
  53. BoolVariable('use_thinlto', 'Use ThinLTO', False),
  54. ]
  55. def get_flags():
  56. return [
  57. ]
  58. def build_res_file(target, source, env):
  59. if (env["bits"] == "32"):
  60. cmdbase = env['mingw_prefix_32']
  61. else:
  62. cmdbase = env['mingw_prefix_64']
  63. cmdbase = cmdbase + 'windres --include-dir . '
  64. import subprocess
  65. for x in range(len(source)):
  66. cmd = cmdbase + '-i ' + str(source[x]) + ' -o ' + str(target[x])
  67. try:
  68. out = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE).communicate()
  69. if len(out[1]):
  70. return 1
  71. except:
  72. return 1
  73. return 0
  74. def setup_msvc_manual(env):
  75. """Set up env to use MSVC manually, using VCINSTALLDIR"""
  76. if (env["bits"] != "default"):
  77. print("""
  78. Bits argument is not supported for MSVC compilation. Architecture depends on the Native/Cross Compile Tools Prompt/Developer Console
  79. (or Visual Studio settings) that is being used to run SCons. As a consequence, bits argument is disabled. Run scons again without bits
  80. argument (example: scons p=windows) and SCons will attempt to detect what MSVC compiler will be executed and inform you.
  81. """)
  82. raise SCons.Errors.UserError("Bits argument should not be used when using VCINSTALLDIR")
  83. # Force bits arg
  84. # (Actually msys2 mingw can support 64-bit, we could detect that)
  85. env["bits"] = "32"
  86. env["x86_libtheora_opt_vc"] = True
  87. # find compiler manually
  88. compiler_version_str = methods.detect_visual_c_compiler_version(env['ENV'])
  89. print("Found MSVC compiler: " + compiler_version_str)
  90. # If building for 64bit architecture, disable assembly optimisations for 32 bit builds (theora as of writing)... vc compiler for 64bit can not compile _asm
  91. if(compiler_version_str == "amd64" or compiler_version_str == "x86_amd64"):
  92. env["bits"] = "64"
  93. env["x86_libtheora_opt_vc"] = False
  94. print("Compiled program architecture will be a 64 bit executable (forcing bits=64).")
  95. elif (compiler_version_str == "x86" or compiler_version_str == "amd64_x86"):
  96. print("Compiled program architecture will be a 32 bit executable. (forcing bits=32).")
  97. else:
  98. print("Failed to manually detect MSVC compiler architecture version... Defaulting to 32bit executable settings (forcing bits=32). Compilation attempt will continue, but SCons can not detect for what architecture this build is compiled for. You should check your settings/compilation setup, or avoid setting VCINSTALLDIR.")
  99. def setup_msvc_auto(env):
  100. """Set up MSVC using SCons's auto-detection logic"""
  101. # If MSVC_VERSION is set by SCons, we know MSVC is installed.
  102. # But we may want a different version or target arch.
  103. # The env may have already been set up with default MSVC tools, so
  104. # reset a few things so we can set it up with the tools we want.
  105. # (Ideally we'd decide on the tool config before configuring any
  106. # environment, and just set the env up once, but this function runs
  107. # on an existing env so this is the simplest way.)
  108. env['MSVC_SETUP_RUN'] = False # Need to set this to re-run the tool
  109. env['MSVS_VERSION'] = None
  110. env['MSVC_VERSION'] = None
  111. env['TARGET_ARCH'] = None
  112. if env['bits'] != 'default':
  113. env['TARGET_ARCH'] = {'32': 'x86', '64': 'x86_64'}[env['bits']]
  114. if env.has_key('msvc_version'):
  115. env['MSVC_VERSION'] = env['msvc_version']
  116. env.Tool('msvc')
  117. env.Tool('mssdk') # we want the MS SDK
  118. # Note: actual compiler version can be found in env['MSVC_VERSION'], e.g. "14.1" for VS2015
  119. # Get actual target arch into bits (it may be "default" at this point):
  120. if env['TARGET_ARCH'] in ('amd64', 'x86_64'):
  121. env['bits'] = '64'
  122. else:
  123. env['bits'] = '32'
  124. print(" Found MSVC version %s, arch %s, bits=%s" % (env['MSVC_VERSION'], env['TARGET_ARCH'], env['bits']))
  125. if env['TARGET_ARCH'] in ('amd64', 'x86_64'):
  126. env["x86_libtheora_opt_vc"] = False
  127. def setup_mingw(env):
  128. """Set up env for use with mingw"""
  129. # Nothing to do here
  130. print("Using Mingw")
  131. pass
  132. def configure_msvc(env, manual_msvc_config):
  133. """Configure env to work with MSVC"""
  134. # Build type
  135. if (env["target"] == "release"):
  136. if (env["optimize"] == "speed"): #optimize for speed (default)
  137. env.Append(CCFLAGS=['/O2'])
  138. else: # optimize for size
  139. env.Append(CCFLAGS=['/O1'])
  140. env.Append(LINKFLAGS=['/SUBSYSTEM:WINDOWS'])
  141. env.Append(LINKFLAGS=['/ENTRY:mainCRTStartup'])
  142. env.Append(LINKFLAGS=['/OPT:REF'])
  143. elif (env["target"] == "release_debug"):
  144. if (env["optimize"] == "speed"): #optimize for speed (default)
  145. env.Append(CCFLAGS=['/O2'])
  146. else: # optimize for size
  147. env.Append(CCFLAGS=['/O1'])
  148. env.AppendUnique(CPPDEFINES = ['DEBUG_ENABLED'])
  149. env.Append(LINKFLAGS=['/SUBSYSTEM:CONSOLE'])
  150. env.Append(LINKFLAGS=['/OPT:REF'])
  151. elif (env["target"] == "debug"):
  152. env.AppendUnique(CCFLAGS=['/Z7', '/Od', '/EHsc'])
  153. env.AppendUnique(CPPDEFINES = ['DEBUG_ENABLED', 'DEBUG_MEMORY_ENABLED',
  154. 'D3D_DEBUG_INFO'])
  155. env.Append(LINKFLAGS=['/SUBSYSTEM:CONSOLE'])
  156. env.Append(LINKFLAGS=['/DEBUG'])
  157. if (env["debug_symbols"] == "full" or env["debug_symbols"] == "yes"):
  158. env.AppendUnique(CCFLAGS=['/Z7'])
  159. env.AppendUnique(LINKFLAGS=['/DEBUG'])
  160. ## Compile/link flags
  161. env.AppendUnique(CCFLAGS=['/MT', '/Gd', '/GR', '/nologo'])
  162. if int(env['MSVC_VERSION'].split('.')[0]) >= 14: #vs2015 and later
  163. env.AppendUnique(CCFLAGS=['/utf-8'])
  164. env.AppendUnique(CXXFLAGS=['/TP']) # assume all sources are C++
  165. if manual_msvc_config: # should be automatic if SCons found it
  166. if os.getenv("WindowsSdkDir") is not None:
  167. env.Prepend(CPPPATH=[os.getenv("WindowsSdkDir") + "/Include"])
  168. else:
  169. print("Missing environment variable: WindowsSdkDir")
  170. env.AppendUnique(CPPDEFINES = ['WINDOWS_ENABLED', 'OPENGL_ENABLED',
  171. 'WASAPI_ENABLED', 'WINMIDI_ENABLED',
  172. 'TYPED_METHOD_BIND',
  173. 'WIN32', 'MSVC',
  174. 'WINVER=%s' % env["target_win_version"],
  175. '_WIN32_WINNT=%s' % env["target_win_version"]])
  176. env.AppendUnique(CPPDEFINES=['NOMINMAX']) # disable bogus min/max WinDef.h macros
  177. if env["bits"] == "64":
  178. env.AppendUnique(CPPDEFINES=['_WIN64'])
  179. ## Libs
  180. LIBS = ['winmm', 'opengl32', 'dsound', 'kernel32', 'ole32', 'oleaut32',
  181. 'user32', 'gdi32', 'IPHLPAPI', 'Shlwapi', 'wsock32', 'Ws2_32',
  182. 'shell32', 'advapi32', 'dinput8', 'dxguid', 'imm32', 'bcrypt','Avrt']
  183. env.Append(LINKFLAGS=[p + env["LIBSUFFIX"] for p in LIBS])
  184. if manual_msvc_config:
  185. if os.getenv("WindowsSdkDir") is not None:
  186. env.Append(LIBPATH=[os.getenv("WindowsSdkDir") + "/Lib"])
  187. else:
  188. print("Missing environment variable: WindowsSdkDir")
  189. ## LTO
  190. if (env["use_lto"]):
  191. env.AppendUnique(CCFLAGS=['/GL'])
  192. env.AppendUnique(ARFLAGS=['/LTCG'])
  193. if env["progress"]:
  194. env.AppendUnique(LINKFLAGS=['/LTCG:STATUS'])
  195. else:
  196. env.AppendUnique(LINKFLAGS=['/LTCG'])
  197. if manual_msvc_config:
  198. env.Prepend(CPPPATH=[p for p in os.getenv("INCLUDE").split(";")])
  199. env.Append(LIBPATH=[p for p in os.getenv("LIB").split(";")])
  200. # Incremental linking fix
  201. env['BUILDERS']['ProgramOriginal'] = env['BUILDERS']['Program']
  202. env['BUILDERS']['Program'] = methods.precious_program
  203. def configure_mingw(env):
  204. # Workaround for MinGW. See:
  205. # http://www.scons.org/wiki/LongCmdLinesOnWin32
  206. env.use_windows_spawn_fix()
  207. ## Build type
  208. if (env["target"] == "release"):
  209. env.Append(CCFLAGS=['-msse2'])
  210. if (env["optimize"] == "speed"): #optimize for speed (default)
  211. if (env["bits"] == "64"):
  212. env.Append(CCFLAGS=['-O3'])
  213. else:
  214. env.Append(CCFLAGS=['-O2'])
  215. else: #optimize for size
  216. env.Prepend(CCFLAGS=['-Os'])
  217. env.Append(LINKFLAGS=['-Wl,--subsystem,windows'])
  218. if (env["debug_symbols"] == "yes"):
  219. env.Prepend(CCFLAGS=['-g1'])
  220. if (env["debug_symbols"] == "full"):
  221. env.Prepend(CCFLAGS=['-g2'])
  222. elif (env["target"] == "release_debug"):
  223. env.Append(CCFLAGS=['-O2'])
  224. env.Append(CPPDEFINES=['DEBUG_ENABLED'])
  225. if (env["debug_symbols"] == "yes"):
  226. env.Prepend(CCFLAGS=['-g1'])
  227. if (env["debug_symbols"] == "full"):
  228. env.Prepend(CCFLAGS=['-g2'])
  229. if (env["optimize"] == "speed"): #optimize for speed (default)
  230. env.Append(CCFLAGS=['-O2'])
  231. else: #optimize for size
  232. env.Prepend(CCFLAGS=['-Os'])
  233. elif (env["target"] == "debug"):
  234. env.Append(CCFLAGS=['-g3'])
  235. env.Append(CPPDEFINES=['DEBUG_ENABLED', 'DEBUG_MEMORY_ENABLED'])
  236. ## Compiler configuration
  237. if (os.name == "nt"):
  238. env['ENV']['TMP'] = os.environ['TMP'] # way to go scons, you can be so stupid sometimes
  239. else:
  240. env["PROGSUFFIX"] = env["PROGSUFFIX"] + ".exe" # for linux cross-compilation
  241. if (env["bits"] == "default"):
  242. if (os.name == "nt"):
  243. env["bits"] = "64" if "PROGRAMFILES(X86)" in os.environ else "32"
  244. else: # default to 64-bit on Linux
  245. env["bits"] = "64"
  246. mingw_prefix = ""
  247. if (env["bits"] == "32"):
  248. env.Append(LINKFLAGS=['-static'])
  249. env.Append(LINKFLAGS=['-static-libgcc'])
  250. env.Append(LINKFLAGS=['-static-libstdc++'])
  251. mingw_prefix = env["mingw_prefix_32"]
  252. else:
  253. env.Append(LINKFLAGS=['-static'])
  254. mingw_prefix = env["mingw_prefix_64"]
  255. if env['use_llvm']:
  256. env["CC"] = mingw_prefix + "clang"
  257. env['AS'] = mingw_prefix + "as"
  258. env["CXX"] = mingw_prefix + "clang++"
  259. env['AR'] = mingw_prefix + "ar"
  260. env['RANLIB'] = mingw_prefix + "ranlib"
  261. env["LINK"] = mingw_prefix + "clang++"
  262. else:
  263. env["CC"] = mingw_prefix + "gcc"
  264. env['AS'] = mingw_prefix + "as"
  265. env['CXX'] = mingw_prefix + "g++"
  266. env['AR'] = mingw_prefix + "gcc-ar"
  267. env['RANLIB'] = mingw_prefix + "gcc-ranlib"
  268. env['LINK'] = mingw_prefix + "g++"
  269. env["x86_libtheora_opt_gcc"] = True
  270. if env['use_lto']:
  271. if not env['use_llvm'] and env.GetOption("num_jobs") > 1:
  272. env.Append(CCFLAGS=['-flto'])
  273. env.Append(LINKFLAGS=['-flto=' + str(env.GetOption("num_jobs"))])
  274. else:
  275. if env['use_thinlto']:
  276. env.Append(CCFLAGS=['-flto=thin'])
  277. env.Append(LINKFLAGS=['-flto=thin'])
  278. else:
  279. env.Append(CCFLAGS=['-flto'])
  280. env.Append(LINKFLAGS=['-flto'])
  281. ## Compile flags
  282. env.Append(CCFLAGS=['-mwindows'])
  283. env.Append(CPPDEFINES=['WINDOWS_ENABLED', 'OPENGL_ENABLED', 'WASAPI_ENABLED', 'WINMIDI_ENABLED'])
  284. env.Append(CPPDEFINES=[('WINVER', env['target_win_version']), ('_WIN32_WINNT', env['target_win_version'])])
  285. env.Append(LIBS=['mingw32', 'opengl32', 'dsound', 'ole32', 'd3d9', 'winmm', 'gdi32', 'iphlpapi', 'shlwapi', 'wsock32', 'ws2_32', 'kernel32', 'oleaut32', 'dinput8', 'dxguid', 'ksuser', 'imm32', 'bcrypt', 'avrt', 'uuid'])
  286. env.Append(CPPDEFINES=['MINGW_ENABLED', ('MINGW_HAS_SECURE_API', 1)])
  287. # resrc
  288. env.Append(BUILDERS={'RES': env.Builder(action=build_res_file, suffix='.o', src_suffix='.rc')})
  289. def configure(env):
  290. # At this point the env has been set up with basic tools/compilers.
  291. env.Prepend(CPPPATH=['#platform/windows'])
  292. print("Configuring for Windows: target=%s, bits=%s" % (env['target'], env['bits']))
  293. if (os.name == "nt"):
  294. env['ENV'] = os.environ # this makes build less repeatable, but simplifies some things
  295. env['ENV']['TMP'] = os.environ['TMP']
  296. # First figure out which compiler, version, and target arch we're using
  297. if os.getenv("VCINSTALLDIR") and not env["use_mingw"]:
  298. # Manual setup of MSVC
  299. setup_msvc_manual(env)
  300. env.msvc = True
  301. manual_msvc_config = True
  302. elif env.get('MSVC_VERSION', '') and not env["use_mingw"]:
  303. setup_msvc_auto(env)
  304. env.msvc = True
  305. manual_msvc_config = False
  306. else:
  307. setup_mingw(env)
  308. env.msvc = False
  309. # Now set compiler/linker flags
  310. if env.msvc:
  311. configure_msvc(env, manual_msvc_config)
  312. else: # MinGW
  313. configure_mingw(env)