SConstruct 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. #!/usr/bin/env python
  2. EnsureSConsVersion(0, 98, 1)
  3. # System
  4. import glob
  5. import os
  6. import string
  7. import sys
  8. # Local
  9. import methods
  10. import gles_builders
  11. from platform_methods import run_in_subprocess
  12. # scan possible build platforms
  13. platform_list = [] # list of platforms
  14. platform_opts = {} # options for each platform
  15. platform_flags = {} # flags for each platform
  16. active_platforms = []
  17. active_platform_ids = []
  18. platform_exporters = []
  19. platform_apis = []
  20. for x in sorted(glob.glob("platform/*")):
  21. if (not os.path.isdir(x) or not os.path.exists(x + "/detect.py")):
  22. continue
  23. tmppath = "./" + x
  24. sys.path.insert(0, tmppath)
  25. import detect
  26. if (os.path.exists(x + "/export/export.cpp")):
  27. platform_exporters.append(x[9:])
  28. if (os.path.exists(x + "/api/api.cpp")):
  29. platform_apis.append(x[9:])
  30. if (detect.is_active()):
  31. active_platforms.append(detect.get_name())
  32. active_platform_ids.append(x)
  33. if (detect.can_build()):
  34. x = x.replace("platform/", "") # rest of world
  35. x = x.replace("platform\\", "") # win32
  36. platform_list += [x]
  37. platform_opts[x] = detect.get_opts()
  38. platform_flags[x] = detect.get_flags()
  39. sys.path.remove(tmppath)
  40. sys.modules.pop('detect')
  41. module_list = methods.detect_modules()
  42. methods.save_active_platforms(active_platforms, active_platform_ids)
  43. custom_tools = ['default']
  44. platform_arg = ARGUMENTS.get("platform", ARGUMENTS.get("p", False))
  45. if os.name == "nt" and (platform_arg == "android" or ARGUMENTS.get("use_mingw", False)):
  46. custom_tools = ['mingw']
  47. elif platform_arg == 'javascript':
  48. # Use generic POSIX build toolchain for Emscripten.
  49. custom_tools = ['cc', 'c++', 'ar', 'link', 'textfile', 'zip']
  50. env_base = Environment(tools=custom_tools)
  51. if 'TERM' in os.environ:
  52. env_base['ENV']['TERM'] = os.environ['TERM']
  53. env_base.AppendENVPath('PATH', os.getenv('PATH'))
  54. env_base.AppendENVPath('PKG_CONFIG_PATH', os.getenv('PKG_CONFIG_PATH'))
  55. env_base.android_maven_repos = []
  56. env_base.android_flat_dirs = []
  57. env_base.android_dependencies = []
  58. env_base.android_gradle_plugins = []
  59. env_base.android_gradle_classpath = []
  60. env_base.android_java_dirs = []
  61. env_base.android_res_dirs = []
  62. env_base.android_asset_dirs = []
  63. env_base.android_aidl_dirs = []
  64. env_base.android_jni_dirs = []
  65. env_base.android_default_config = []
  66. env_base.android_manifest_chunk = ""
  67. env_base.android_permission_chunk = ""
  68. env_base.android_appattributes_chunk = ""
  69. env_base.disabled_modules = []
  70. env_base.use_ptrcall = False
  71. env_base.split_drivers = False
  72. env_base.split_modules = False
  73. env_base.module_version_string = ""
  74. env_base.msvc = False
  75. env_base.__class__.android_add_maven_repository = methods.android_add_maven_repository
  76. env_base.__class__.android_add_flat_dir = methods.android_add_flat_dir
  77. env_base.__class__.android_add_dependency = methods.android_add_dependency
  78. env_base.__class__.android_add_java_dir = methods.android_add_java_dir
  79. env_base.__class__.android_add_res_dir = methods.android_add_res_dir
  80. env_base.__class__.android_add_asset_dir = methods.android_add_asset_dir
  81. env_base.__class__.android_add_aidl_dir = methods.android_add_aidl_dir
  82. env_base.__class__.android_add_jni_dir = methods.android_add_jni_dir
  83. env_base.__class__.android_add_default_config = methods.android_add_default_config
  84. env_base.__class__.android_add_to_manifest = methods.android_add_to_manifest
  85. env_base.__class__.android_add_to_permissions = methods.android_add_to_permissions
  86. env_base.__class__.android_add_to_attributes = methods.android_add_to_attributes
  87. env_base.__class__.android_add_gradle_plugin = methods.android_add_gradle_plugin
  88. env_base.__class__.android_add_gradle_classpath = methods.android_add_gradle_classpath
  89. env_base.__class__.disable_module = methods.disable_module
  90. env_base.__class__.add_module_version_string = methods.add_module_version_string
  91. env_base.__class__.add_source_files = methods.add_source_files
  92. env_base.__class__.use_windows_spawn_fix = methods.use_windows_spawn_fix
  93. env_base.__class__.split_lib = methods.split_lib
  94. env_base.__class__.add_shared_library = methods.add_shared_library
  95. env_base.__class__.add_library = methods.add_library
  96. env_base.__class__.add_program = methods.add_program
  97. env_base.__class__.CommandNoCache = methods.CommandNoCache
  98. env_base.__class__.disable_warnings = methods.disable_warnings
  99. env_base["x86_libtheora_opt_gcc"] = False
  100. env_base["x86_libtheora_opt_vc"] = False
  101. # Build options
  102. customs = ['custom.py']
  103. profile = ARGUMENTS.get("profile", False)
  104. if profile:
  105. if os.path.isfile(profile):
  106. customs.append(profile)
  107. elif os.path.isfile(profile + ".py"):
  108. customs.append(profile + ".py")
  109. opts = Variables(customs, ARGUMENTS)
  110. # Target build options
  111. opts.Add('arch', "Platform-dependent architecture (arm/arm64/x86/x64/mips/...)", '')
  112. opts.Add(EnumVariable('bits', "Target platform bits", 'default', ('default', '32', '64')))
  113. opts.Add('p', "Platform (alias for 'platform')", '')
  114. opts.Add('platform', "Target platform (%s)" % ('|'.join(platform_list), ), '')
  115. opts.Add(EnumVariable('target', "Compilation target", 'debug', ('debug', 'release_debug', 'release')))
  116. opts.Add(EnumVariable('optimize', "Optimization type", 'speed', ('speed', 'size')))
  117. opts.Add(BoolVariable('tools', "Build the tools (a.k.a. the Godot editor)", True))
  118. opts.Add(BoolVariable('use_lto', 'Use link-time optimization', False))
  119. opts.Add(BoolVariable('use_precise_math_checks', 'Math checks use very precise epsilon (useful to debug the engine)', False))
  120. # Components
  121. opts.Add(BoolVariable('deprecated', "Enable deprecated features", True))
  122. opts.Add(BoolVariable('gdscript', "Enable GDScript support", True))
  123. opts.Add(BoolVariable('minizip', "Enable ZIP archive support using minizip", True))
  124. opts.Add(BoolVariable('xaudio2', "Enable the XAudio2 audio driver", False))
  125. # Advanced options
  126. opts.Add(BoolVariable('verbose', "Enable verbose output for the compilation", False))
  127. opts.Add(BoolVariable('progress', "Show a progress indicator during compilation", True))
  128. opts.Add(EnumVariable('warnings', "Set the level of warnings emitted during compilation", 'all', ('extra', 'all', 'moderate', 'no')))
  129. opts.Add(BoolVariable('werror', "Treat compiler warnings as errors. Depends on the level of warnings set with 'warnings'", False))
  130. opts.Add(BoolVariable('dev', "If yes, alias for verbose=yes warnings=all", False))
  131. opts.Add('extra_suffix', "Custom extra suffix added to the base filename of all generated binary files", '')
  132. opts.Add(BoolVariable('vsproj', "Generate a Visual Studio solution", False))
  133. opts.Add(EnumVariable('macports_clang', "Build using Clang from MacPorts", 'no', ('no', '5.0', 'devel')))
  134. opts.Add(BoolVariable('disable_3d', "Disable 3D nodes for a smaller executable", False))
  135. opts.Add(BoolVariable('disable_advanced_gui', "Disable advanced GUI nodes and behaviors", False))
  136. opts.Add(BoolVariable('no_editor_splash', "Don't use the custom splash screen for the editor", False))
  137. opts.Add('system_certs_path', "Use this path as SSL certificates default for editor (for package maintainers)", '')
  138. # Thirdparty libraries
  139. opts.Add(BoolVariable('builtin_bullet', "Use the built-in Bullet library", True))
  140. opts.Add(BoolVariable('builtin_certs', "Bundle default SSL certificates to be used if you don't specify an override in the project settings", True))
  141. opts.Add(BoolVariable('builtin_enet', "Use the built-in ENet library", True))
  142. opts.Add(BoolVariable('builtin_freetype', "Use the built-in FreeType library", True))
  143. opts.Add(BoolVariable('builtin_libogg', "Use the built-in libogg library", True))
  144. opts.Add(BoolVariable('builtin_libpng', "Use the built-in libpng library", True))
  145. opts.Add(BoolVariable('builtin_libtheora', "Use the built-in libtheora library", True))
  146. opts.Add(BoolVariable('builtin_libvorbis', "Use the built-in libvorbis library", True))
  147. opts.Add(BoolVariable('builtin_libvpx', "Use the built-in libvpx library", True))
  148. opts.Add(BoolVariable('builtin_libwebp', "Use the built-in libwebp library", True))
  149. opts.Add(BoolVariable('builtin_libwebsockets', "Use the built-in libwebsockets library", True))
  150. opts.Add(BoolVariable('builtin_mbedtls', "Use the built-in mbedTLS library", True))
  151. opts.Add(BoolVariable('builtin_miniupnpc', "Use the built-in miniupnpc library", True))
  152. opts.Add(BoolVariable('builtin_opus', "Use the built-in Opus library", True))
  153. opts.Add(BoolVariable('builtin_pcre2', "Use the built-in PCRE2 library)", True))
  154. opts.Add(BoolVariable('builtin_recast', "Use the built-in Recast library", True))
  155. opts.Add(BoolVariable('builtin_squish', "Use the built-in squish library", True))
  156. opts.Add(BoolVariable('builtin_thekla_atlas', "Use the built-in thekla_altas library", True))
  157. opts.Add(BoolVariable('builtin_xatlas', "Use the built-in xatlas library", True))
  158. opts.Add(BoolVariable('builtin_zlib', "Use the built-in zlib library", True))
  159. opts.Add(BoolVariable('builtin_zstd', "Use the built-in Zstd library", True))
  160. # Compilation environment setup
  161. opts.Add("CXX", "C++ compiler")
  162. opts.Add("CC", "C compiler")
  163. opts.Add("LINK", "Linker")
  164. opts.Add("CCFLAGS", "Custom flags for both the C and C++ compilers")
  165. opts.Add("CXXFLAGS", "Custom flags for the C++ compiler")
  166. opts.Add("CFLAGS", "Custom flags for the C compiler")
  167. opts.Add("LINKFLAGS", "Custom flags for the linker")
  168. # add platform specific options
  169. for k in platform_opts.keys():
  170. opt_list = platform_opts[k]
  171. for o in opt_list:
  172. opts.Add(o)
  173. for x in module_list:
  174. module_enabled = True
  175. tmppath = "./modules/" + x
  176. sys.path.insert(0, tmppath)
  177. import config
  178. enabled_attr = getattr(config, "is_enabled", None)
  179. if (callable(enabled_attr) and not config.is_enabled()):
  180. module_enabled = False
  181. sys.path.remove(tmppath)
  182. sys.modules.pop('config')
  183. opts.Add(BoolVariable('module_' + x + '_enabled', "Enable module '%s'" % (x, ), module_enabled))
  184. opts.Update(env_base) # update environment
  185. Help(opts.GenerateHelpText(env_base)) # generate help
  186. # add default include paths
  187. env_base.Append(CPPPATH=['#editor', '#'])
  188. # configure ENV for platform
  189. env_base.platform_exporters = platform_exporters
  190. env_base.platform_apis = platform_apis
  191. if (env_base["use_precise_math_checks"]):
  192. env_base.Append(CPPDEFINES=['PRECISE_MATH_CHECKS'])
  193. if (env_base['target'] == 'debug'):
  194. env_base.Append(CPPDEFINES=['DEBUG_MEMORY_ALLOC','DISABLE_FORCED_INLINE'])
  195. # The two options below speed up incremental builds, but reduce the certainty that all files
  196. # will properly be rebuilt. As such, we only enable them for debug (dev) builds, not release.
  197. # To decide whether to rebuild a file, use the MD5 sum only if the timestamp has changed.
  198. # http://scons.org/doc/production/HTML/scons-user/ch06.html#idm139837621851792
  199. env_base.Decider('MD5-timestamp')
  200. # Use cached implicit dependencies by default. Can be overridden by specifying `--implicit-deps-changed` in the command line.
  201. # http://scons.org/doc/production/HTML/scons-user/ch06s04.html
  202. env_base.SetOption('implicit_cache', 1)
  203. if (env_base['no_editor_splash']):
  204. env_base.Append(CPPDEFINES=['NO_EDITOR_SPLASH'])
  205. if not env_base['deprecated']:
  206. env_base.Append(CPPDEFINES=['DISABLE_DEPRECATED'])
  207. env_base.platforms = {}
  208. selected_platform = ""
  209. if env_base['platform'] != "":
  210. selected_platform = env_base['platform']
  211. elif env_base['p'] != "":
  212. selected_platform = env_base['p']
  213. env_base["platform"] = selected_platform
  214. if selected_platform in platform_list:
  215. tmppath = "./platform/" + selected_platform
  216. sys.path.insert(0, tmppath)
  217. import detect
  218. if "create" in dir(detect):
  219. env = detect.create(env_base)
  220. else:
  221. env = env_base.Clone()
  222. if env['dev']:
  223. env["warnings"] = "all"
  224. env['verbose'] = True
  225. if env['vsproj']:
  226. env.vs_incs = []
  227. env.vs_srcs = []
  228. def AddToVSProject(sources):
  229. for x in sources:
  230. if type(x) == type(""):
  231. fname = env.File(x).path
  232. else:
  233. fname = env.File(x)[0].path
  234. pieces = fname.split(".")
  235. if len(pieces) > 0:
  236. basename = pieces[0]
  237. basename = basename.replace('\\\\', '/')
  238. if os.path.isfile(basename + ".h"):
  239. env.vs_incs = env.vs_incs + [basename + ".h"]
  240. elif os.path.isfile(basename + ".hpp"):
  241. env.vs_incs = env.vs_incs + [basename + ".hpp"]
  242. if os.path.isfile(basename + ".c"):
  243. env.vs_srcs = env.vs_srcs + [basename + ".c"]
  244. elif os.path.isfile(basename + ".cpp"):
  245. env.vs_srcs = env.vs_srcs + [basename + ".cpp"]
  246. env.AddToVSProject = AddToVSProject
  247. env.extra_suffix = ""
  248. if env["extra_suffix"] != '':
  249. env.extra_suffix += '.' + env["extra_suffix"]
  250. CCFLAGS = env.get('CCFLAGS', '')
  251. env['CCFLAGS'] = ''
  252. env.Append(CCFLAGS=str(CCFLAGS).split())
  253. CFLAGS = env.get('CFLAGS', '')
  254. env['CFLAGS'] = ''
  255. env.Append(CFLAGS=str(CFLAGS).split())
  256. LINKFLAGS = env.get('LINKFLAGS', '')
  257. env['LINKFLAGS'] = ''
  258. env.Append(LINKFLAGS=str(LINKFLAGS).split())
  259. flag_list = platform_flags[selected_platform]
  260. for f in flag_list:
  261. if not (f[0] in ARGUMENTS): # allow command line to override platform flags
  262. env[f[0]] = f[1]
  263. # must happen after the flags, so when flags are used by configure, stuff happens (ie, ssl on x11)
  264. detect.configure(env)
  265. # Configure compiler warnings
  266. if env.msvc:
  267. # Truncations, narrowing conversions, signed/unsigned comparisons...
  268. disable_nonessential_warnings = ['/wd4267', '/wd4244', '/wd4305', '/wd4018', '/wd4800']
  269. if (env["warnings"] == 'extra'):
  270. env.Append(CCFLAGS=['/Wall']) # Implies /W4
  271. elif (env["warnings"] == 'all'):
  272. env.Append(CCFLAGS=['/W3'] + disable_nonessential_warnings)
  273. elif (env["warnings"] == 'moderate'):
  274. env.Append(CCFLAGS=['/W2'] + disable_nonessential_warnings)
  275. else: # 'no'
  276. env.Append(CCFLAGS=['/w'])
  277. # Set exception handling model to avoid warnings caused by Windows system headers.
  278. env.Append(CCFLAGS=['/EHsc'])
  279. if (env["werror"]):
  280. env.Append(CCFLAGS=['/WX'])
  281. else: # Rest of the world
  282. shadow_local_warning = []
  283. all_plus_warnings = ['-Wwrite-strings']
  284. if methods.use_gcc(env):
  285. version = methods.get_compiler_version(env)
  286. if version != None and version[0] >= '7':
  287. shadow_local_warning = ['-Wshadow-local']
  288. if (env["warnings"] == 'extra'):
  289. env.Append(CCFLAGS=['-Wall', '-Wextra'] + all_plus_warnings + shadow_local_warning)
  290. elif (env["warnings"] == 'all'):
  291. env.Append(CCFLAGS=['-Wall'] + shadow_local_warning)
  292. elif (env["warnings"] == 'moderate'):
  293. env.Append(CCFLAGS=['-Wall', '-Wno-unused'] + shadow_local_warning)
  294. else: # 'no'
  295. env.Append(CCFLAGS=['-w'])
  296. if (env["werror"]):
  297. env.Append(CCFLAGS=['-Werror'])
  298. else: # always enable those errors
  299. env.Append(CCFLAGS=['-Werror=return-type'])
  300. if (hasattr(detect, 'get_program_suffix')):
  301. suffix = "." + detect.get_program_suffix()
  302. else:
  303. suffix = "." + selected_platform
  304. if (env["target"] == "release"):
  305. if env["tools"]:
  306. print("Tools can only be built with targets 'debug' and 'release_debug'.")
  307. sys.exit(255)
  308. suffix += ".opt"
  309. env.Append(CPPDEFINES=['NDEBUG'])
  310. elif (env["target"] == "release_debug"):
  311. if env["tools"]:
  312. suffix += ".opt.tools"
  313. else:
  314. suffix += ".opt.debug"
  315. else:
  316. if env["tools"]:
  317. suffix += ".tools"
  318. else:
  319. suffix += ".debug"
  320. if env["arch"] != "":
  321. suffix += "." + env["arch"]
  322. elif (env["bits"] == "32"):
  323. suffix += ".32"
  324. elif (env["bits"] == "64"):
  325. suffix += ".64"
  326. suffix += env.extra_suffix
  327. sys.path.remove(tmppath)
  328. sys.modules.pop('detect')
  329. env.module_list = []
  330. env.doc_class_path = {}
  331. for x in module_list:
  332. if not env['module_' + x + '_enabled']:
  333. continue
  334. tmppath = "./modules/" + x
  335. sys.path.insert(0, tmppath)
  336. env.current_module = x
  337. import config
  338. # can_build changed number of arguments between 3.0 (1) and 3.1 (2),
  339. # so try both to preserve compatibility for 3.0 modules
  340. can_build = False
  341. try:
  342. can_build = config.can_build(env, selected_platform)
  343. except TypeError:
  344. print("Warning: module '%s' uses a deprecated `can_build` "
  345. "signature in its config.py file, it should be "
  346. "`can_build(env, platform)`." % x)
  347. can_build = config.can_build(selected_platform)
  348. if (can_build):
  349. config.configure(env)
  350. env.module_list.append(x)
  351. try:
  352. doc_classes = config.get_doc_classes()
  353. doc_path = config.get_doc_path()
  354. for c in doc_classes:
  355. env.doc_class_path[c] = "modules/" + x + "/" + doc_path
  356. except:
  357. pass
  358. sys.path.remove(tmppath)
  359. sys.modules.pop('config')
  360. methods.update_version(env.module_version_string)
  361. env["PROGSUFFIX"] = suffix + env.module_version_string + env["PROGSUFFIX"]
  362. env["OBJSUFFIX"] = suffix + env["OBJSUFFIX"]
  363. # (SH)LIBSUFFIX will be used for our own built libraries
  364. # LIBSUFFIXES contains LIBSUFFIX and SHLIBSUFFIX by default,
  365. # so we need to append the default suffixes to keep the ability
  366. # to link against thirdparty libraries (.a, .so, .lib, etc.).
  367. if os.name == "nt":
  368. # On Windows, only static libraries and import libraries can be
  369. # statically linked - both using .lib extension
  370. env["LIBSUFFIXES"] += [env["LIBSUFFIX"]]
  371. else:
  372. env["LIBSUFFIXES"] += [env["LIBSUFFIX"], env["SHLIBSUFFIX"]]
  373. env["LIBSUFFIX"] = suffix + env["LIBSUFFIX"]
  374. env["SHLIBSUFFIX"] = suffix + env["SHLIBSUFFIX"]
  375. if (env.use_ptrcall):
  376. env.Append(CPPDEFINES=['PTRCALL_ENABLED'])
  377. if env['tools']:
  378. env.Append(CPPDEFINES=['TOOLS_ENABLED'])
  379. if env['disable_3d']:
  380. if env['tools']:
  381. print("Build option 'disable_3d=yes' cannot be used with 'tools=yes' (editor), only with 'tools=no' (export template).")
  382. sys.exit(255)
  383. else:
  384. env.Append(CPPDEFINES=['_3D_DISABLED'])
  385. if env['gdscript']:
  386. env.Append(CPPDEFINES=['GDSCRIPT_ENABLED'])
  387. if env['disable_advanced_gui']:
  388. if env['tools']:
  389. print("Build option 'disable_advanced_gui=yes' cannot be used with 'tools=yes' (editor), only with 'tools=no' (export template).")
  390. sys.exit(255)
  391. else:
  392. env.Append(CPPDEFINES=['ADVANCED_GUI_DISABLED'])
  393. if env['minizip']:
  394. env.Append(CPPDEFINES=['MINIZIP_ENABLED'])
  395. if not env['verbose']:
  396. methods.no_verbose(sys, env)
  397. if (not env["platform"] == "server"): # FIXME: detect GLES3
  398. env.Append(BUILDERS = { 'GLES3_GLSL' : env.Builder(action=run_in_subprocess(gles_builders.build_gles3_headers), suffix='glsl.gen.h', src_suffix='.glsl')})
  399. env.Append(BUILDERS = { 'GLES2_GLSL' : env.Builder(action=run_in_subprocess(gles_builders.build_gles2_headers), suffix='glsl.gen.h', src_suffix='.glsl')})
  400. scons_cache_path = os.environ.get("SCONS_CACHE")
  401. if scons_cache_path != None:
  402. CacheDir(scons_cache_path)
  403. print("Scons cache enabled... (path: '" + scons_cache_path + "')")
  404. Export('env')
  405. # build subdirs, the build order is dependent on link order.
  406. SConscript("core/SCsub")
  407. SConscript("servers/SCsub")
  408. SConscript("scene/SCsub")
  409. SConscript("editor/SCsub")
  410. SConscript("drivers/SCsub")
  411. SConscript("platform/SCsub")
  412. SConscript("modules/SCsub")
  413. SConscript("main/SCsub")
  414. SConscript("platform/" + selected_platform + "/SCsub") # build selected platform
  415. # Microsoft Visual Studio Project Generation
  416. if env['vsproj']:
  417. env['CPPPATH'] = [Dir(path) for path in env['CPPPATH']]
  418. methods.generate_vs_project(env, GetOption("num_jobs"))
  419. methods.generate_cpp_hint_file("cpp.hint")
  420. # Check for the existence of headers
  421. conf = Configure(env)
  422. if ("check_c_headers" in env):
  423. for header in env["check_c_headers"]:
  424. if (conf.CheckCHeader(header[0])):
  425. env.AppendUnique(CPPDEFINES=[header[1]])
  426. else:
  427. print("No valid target platform selected.")
  428. print("The following platforms were detected:")
  429. for x in platform_list:
  430. print("\t" + x)
  431. print("\nPlease run SCons again with the argument: platform=<string>")
  432. # The following only makes sense when the env is defined, and assumes it is
  433. if 'env' in locals():
  434. screen = sys.stdout
  435. # Progress reporting is not available in non-TTY environments since it
  436. # messes with the output (for example, when writing to a file)
  437. show_progress = (env['progress'] and sys.stdout.isatty())
  438. node_count = 0
  439. node_count_max = 0
  440. node_count_interval = 1
  441. node_count_fname = str(env.Dir('#')) + '/.scons_node_count'
  442. import time, math
  443. class cache_progress:
  444. # The default is 1 GB cache and 12 hours half life
  445. def __init__(self, path = None, limit = 1073741824, half_life = 43200):
  446. self.path = path
  447. self.limit = limit
  448. self.exponent_scale = math.log(2) / half_life
  449. if env['verbose'] and path != None:
  450. screen.write('Current cache limit is ' + self.convert_size(limit) + ' (used: ' + self.convert_size(self.get_size(path)) + ')\n')
  451. self.delete(self.file_list())
  452. def __call__(self, node, *args, **kw):
  453. global node_count, node_count_max, node_count_interval, node_count_fname, show_progress
  454. if show_progress:
  455. # Print the progress percentage
  456. node_count += node_count_interval
  457. if (node_count_max > 0 and node_count <= node_count_max):
  458. screen.write('\r[%3d%%] ' % (node_count * 100 / node_count_max))
  459. screen.flush()
  460. elif (node_count_max > 0 and node_count > node_count_max):
  461. screen.write('\r[100%] ')
  462. screen.flush()
  463. else:
  464. screen.write('\r[Initial build] ')
  465. screen.flush()
  466. def delete(self, files):
  467. if len(files) == 0:
  468. return
  469. if env['verbose']:
  470. # Utter something
  471. screen.write('\rPurging %d %s from cache...\n' % (len(files), len(files) > 1 and 'files' or 'file'))
  472. [os.remove(f) for f in files]
  473. def file_list(self):
  474. if self.path is None:
  475. # Nothing to do
  476. return []
  477. # Gather a list of (filename, (size, atime)) within the
  478. # cache directory
  479. file_stat = [(x, os.stat(x)[6:8]) for x in glob.glob(os.path.join(self.path, '*', '*'))]
  480. if file_stat == []:
  481. # Nothing to do
  482. return []
  483. # Weight the cache files by size (assumed to be roughly
  484. # proportional to the recompilation time) times an exponential
  485. # decay since the ctime, and return a list with the entries
  486. # (filename, size, weight).
  487. current_time = time.time()
  488. file_stat = [(x[0], x[1][0], (current_time - x[1][1])) for x in file_stat]
  489. # Sort by the most resently accessed files (most sensible to keep) first
  490. file_stat.sort(key=lambda x: x[2])
  491. # Search for the first entry where the storage limit is
  492. # reached
  493. sum, mark = 0, None
  494. for i,x in enumerate(file_stat):
  495. sum += x[1]
  496. if sum > self.limit:
  497. mark = i
  498. break
  499. if mark is None:
  500. return []
  501. else:
  502. return [x[0] for x in file_stat[mark:]]
  503. def convert_size(self, size_bytes):
  504. if size_bytes == 0:
  505. return "0 bytes"
  506. size_name = ("bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
  507. i = int(math.floor(math.log(size_bytes, 1024)))
  508. p = math.pow(1024, i)
  509. s = round(size_bytes / p, 2)
  510. return "%s %s" % (int(s) if i == 0 else s, size_name[i])
  511. def get_size(self, start_path = '.'):
  512. total_size = 0
  513. for dirpath, dirnames, filenames in os.walk(start_path):
  514. for f in filenames:
  515. fp = os.path.join(dirpath, f)
  516. total_size += os.path.getsize(fp)
  517. return total_size
  518. def progress_finish(target, source, env):
  519. global node_count, progressor
  520. with open(node_count_fname, 'w') as f:
  521. f.write('%d\n' % node_count)
  522. progressor.delete(progressor.file_list())
  523. try:
  524. with open(node_count_fname) as f:
  525. node_count_max = int(f.readline())
  526. except:
  527. pass
  528. cache_directory = os.environ.get("SCONS_CACHE")
  529. # Simple cache pruning, attached to SCons' progress callback. Trim the
  530. # cache directory to a size not larger than cache_limit.
  531. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", 1024)) * 1024 * 1024
  532. progressor = cache_progress(cache_directory, cache_limit)
  533. Progress(progressor, interval = node_count_interval)
  534. progress_finish_command = Command('progress_finish', [], progress_finish)
  535. AlwaysBuild(progress_finish_command)