SConstruct 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. #!/usr/bin/env python
  2. import os
  3. import sys
  4. import subprocess
  5. if sys.version_info < (3,):
  6. def decode_utf8(x):
  7. return x
  8. else:
  9. import codecs
  10. def decode_utf8(x):
  11. return codecs.utf_8_decode(x)[0]
  12. # Workaround for MinGW. See:
  13. # http://www.scons.org/wiki/LongCmdLinesOnWin32
  14. if os.name == "nt":
  15. import subprocess
  16. def mySubProcess(cmdline, env):
  17. # print "SPAWNED : " + cmdline
  18. startupinfo = subprocess.STARTUPINFO()
  19. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  20. proc = subprocess.Popen(
  21. cmdline,
  22. stdin=subprocess.PIPE,
  23. stdout=subprocess.PIPE,
  24. stderr=subprocess.PIPE,
  25. startupinfo=startupinfo,
  26. shell=False,
  27. env=env,
  28. )
  29. data, err = proc.communicate()
  30. rv = proc.wait()
  31. if rv:
  32. print("=====")
  33. print(err.decode("utf-8"))
  34. print("=====")
  35. return rv
  36. def mySpawn(sh, escape, cmd, args, env):
  37. newargs = " ".join(args[1:])
  38. cmdline = cmd + " " + newargs
  39. rv = 0
  40. if len(cmdline) > 32000 and cmd.endswith("ar"):
  41. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  42. for i in range(3, len(args)):
  43. rv = mySubProcess(cmdline + args[i], env)
  44. if rv:
  45. break
  46. else:
  47. rv = mySubProcess(cmdline, env)
  48. return rv
  49. def add_sources(sources, dir, extension):
  50. for f in os.listdir(dir):
  51. if f.endswith("." + extension):
  52. sources.append(dir + "/" + f)
  53. # Try to detect the host platform automatically.
  54. # This is used if no `platform` argument is passed
  55. if sys.platform.startswith("linux"):
  56. host_platform = "linux"
  57. elif sys.platform.startswith("freebsd"):
  58. host_platform = "freebsd"
  59. elif sys.platform == "darwin":
  60. host_platform = "osx"
  61. elif sys.platform == "win32" or sys.platform == "msys":
  62. host_platform = "windows"
  63. else:
  64. raise ValueError("Could not detect platform automatically, please specify with platform=<platform>")
  65. env = Environment(ENV=os.environ)
  66. # Default num_jobs to local cpu count if not user specified.
  67. # SCons has a peculiarity where user-specified options won't be overridden
  68. # by SetOption, so we can rely on this to know if we should use our default.
  69. initial_num_jobs = env.GetOption("num_jobs")
  70. altered_num_jobs = initial_num_jobs + 1
  71. env.SetOption("num_jobs", altered_num_jobs)
  72. # os.cpu_count() requires Python 3.4+.
  73. if hasattr(os, "cpu_count") and env.GetOption("num_jobs") == altered_num_jobs:
  74. cpu_count = os.cpu_count()
  75. if cpu_count is None:
  76. print("Couldn't auto-detect CPU count to configure build parallelism. Specify it with the -j argument.")
  77. else:
  78. safer_cpu_count = cpu_count if cpu_count <= 4 else cpu_count - 1
  79. print(
  80. "Auto-detected %d CPU cores available for build parallelism. Using %d cores by default. You can override it with the -j argument."
  81. % (cpu_count, safer_cpu_count)
  82. )
  83. env.SetOption("num_jobs", safer_cpu_count)
  84. is64 = sys.maxsize > 2 ** 32
  85. if (
  86. env["TARGET_ARCH"] == "amd64"
  87. or env["TARGET_ARCH"] == "emt64"
  88. or env["TARGET_ARCH"] == "x86_64"
  89. or env["TARGET_ARCH"] == "arm64-v8a"
  90. ):
  91. is64 = True
  92. opts = Variables([], ARGUMENTS)
  93. opts.Add(
  94. EnumVariable(
  95. "platform",
  96. "Target platform",
  97. host_platform,
  98. allowed_values=("linux", "freebsd", "osx", "windows", "android", "ios", "javascript"),
  99. ignorecase=2,
  100. )
  101. )
  102. opts.Add(EnumVariable("bits", "Target platform bits", "64" if is64 else "32", ("32", "64")))
  103. opts.Add(BoolVariable("use_llvm", "Use the LLVM compiler - only effective when targeting Linux or FreeBSD", False))
  104. opts.Add(BoolVariable("use_mingw", "Use the MinGW compiler instead of MSVC - only effective on Windows", False))
  105. # Must be the same setting as used for cpp_bindings
  106. opts.Add(EnumVariable("target", "Compilation target", "debug", allowed_values=("debug", "release"), ignorecase=2))
  107. opts.Add(
  108. PathVariable(
  109. "headers_dir",
  110. "Path to the directory containing Godot headers",
  111. "godot-headers",
  112. PathVariable.PathIsDir,
  113. )
  114. )
  115. opts.Add(PathVariable("custom_api_file", "Path to a custom JSON API file", None, PathVariable.PathIsFile))
  116. opts.Add(
  117. EnumVariable(
  118. "generate_bindings",
  119. "Generate GDNative API bindings",
  120. "auto",
  121. allowed_values=["yes", "no", "auto", "true"],
  122. ignorecase=2,
  123. )
  124. )
  125. opts.Add(
  126. EnumVariable(
  127. "android_arch",
  128. "Target Android architecture",
  129. "armv7",
  130. ["armv7", "arm64v8", "x86", "x86_64"],
  131. )
  132. )
  133. opts.Add("macos_deployment_target", "macOS deployment target", "default")
  134. opts.Add("macos_sdk_path", "macOS SDK path", "")
  135. opts.Add(EnumVariable("macos_arch", "Target macOS architecture", "universal", ["universal", "x86_64", "arm64"]))
  136. opts.Add(EnumVariable("ios_arch", "Target iOS architecture", "arm64", ["armv7", "arm64", "x86_64"]))
  137. opts.Add(BoolVariable("ios_simulator", "Target iOS Simulator", False))
  138. opts.Add(
  139. "IPHONEPATH",
  140. "Path to iPhone toolchain",
  141. "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain",
  142. )
  143. opts.Add(
  144. "android_api_level",
  145. "Target Android API level",
  146. "18" if ARGUMENTS.get("android_arch", "armv7") in ["armv7", "x86"] else "21",
  147. )
  148. opts.Add(
  149. "ANDROID_NDK_ROOT",
  150. "Path to your Android NDK installation. By default, uses ANDROID_NDK_ROOT from your defined environment variables.",
  151. os.environ.get("ANDROID_NDK_ROOT", None),
  152. )
  153. opts.Add(
  154. BoolVariable(
  155. "generate_template_get_node",
  156. "Generate a template version of the Node class's get_node.",
  157. True,
  158. )
  159. )
  160. opts.Add(BoolVariable("build_library", "Build the godot-cpp library.", True))
  161. opts.Update(env)
  162. Help(opts.GenerateHelpText(env))
  163. # Detect and print a warning listing unknown SCons variables to ease troubleshooting.
  164. unknown = opts.UnknownVariables()
  165. if unknown:
  166. print("WARNING: Unknown SCons variables were passed and will be ignored:")
  167. for item in unknown.items():
  168. print(" " + item[0] + "=" + item[1])
  169. # This makes sure to keep the session environment variables on Windows.
  170. # This way, you can run SCons in a Visual Studio 2017 prompt and it will find
  171. # all the required tools
  172. if host_platform == "windows" and env["platform"] != "android":
  173. if env["bits"] == "64":
  174. env = Environment(TARGET_ARCH="amd64")
  175. elif env["bits"] == "32":
  176. env = Environment(TARGET_ARCH="x86")
  177. opts.Update(env)
  178. # Require C++14
  179. if host_platform == "windows" and env["platform"] == "windows" and not env["use_mingw"]:
  180. # MSVC
  181. env.Append(CCFLAGS=["/std:c++14"])
  182. else:
  183. env.Append(CCFLAGS=["-std=c++14"])
  184. if env["platform"] == "linux" or env["platform"] == "freebsd":
  185. if env["use_llvm"]:
  186. env["CXX"] = "clang++"
  187. env.Append(CCFLAGS=["-fPIC", "-Wwrite-strings"])
  188. env.Append(LINKFLAGS=["-Wl,-R,'$$ORIGIN'"])
  189. if env["target"] == "debug":
  190. env.Append(CCFLAGS=["-Og", "-g"])
  191. elif env["target"] == "release":
  192. env.Append(CCFLAGS=["-O3"])
  193. if env["bits"] == "64":
  194. env.Append(CCFLAGS=["-m64"])
  195. env.Append(LINKFLAGS=["-m64"])
  196. elif env["bits"] == "32":
  197. env.Append(CCFLAGS=["-m32"])
  198. env.Append(LINKFLAGS=["-m32"])
  199. elif env["platform"] == "osx":
  200. # Use Clang on macOS by default
  201. env["CXX"] = "clang++"
  202. if env["bits"] == "32":
  203. raise ValueError("Only 64-bit builds are supported for the macOS target.")
  204. if env["macos_arch"] == "universal":
  205. env.Append(LINKFLAGS=["-arch", "x86_64", "-arch", "arm64"])
  206. env.Append(CCFLAGS=["-arch", "x86_64", "-arch", "arm64"])
  207. else:
  208. env.Append(LINKFLAGS=["-arch", env["macos_arch"]])
  209. env.Append(CCFLAGS=["-arch", env["macos_arch"]])
  210. if env["macos_deployment_target"] != "default":
  211. env.Append(CCFLAGS=["-mmacosx-version-min=" + env["macos_deployment_target"]])
  212. env.Append(LINKFLAGS=["-mmacosx-version-min=" + env["macos_deployment_target"]])
  213. if env["macos_sdk_path"]:
  214. env.Append(CCFLAGS=["-isysroot", env["macos_sdk_path"]])
  215. env.Append(LINKFLAGS=["-isysroot", env["macos_sdk_path"]])
  216. env.Append(LINKFLAGS=["-Wl,-undefined,dynamic_lookup"])
  217. if env["target"] == "debug":
  218. env.Append(CCFLAGS=["-Og", "-g"])
  219. elif env["target"] == "release":
  220. env.Append(CCFLAGS=["-O3"])
  221. elif env["platform"] == "ios":
  222. if env["ios_simulator"]:
  223. sdk_name = "iphonesimulator"
  224. env.Append(CCFLAGS=["-mios-simulator-version-min=10.0"])
  225. else:
  226. sdk_name = "iphoneos"
  227. env.Append(CCFLAGS=["-miphoneos-version-min=10.0"])
  228. try:
  229. sdk_path = decode_utf8(subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip())
  230. except (subprocess.CalledProcessError, OSError):
  231. raise ValueError("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  232. compiler_path = env["IPHONEPATH"] + "/usr/bin/"
  233. env["ENV"]["PATH"] = env["IPHONEPATH"] + "/Developer/usr/bin/:" + env["ENV"]["PATH"]
  234. env["CC"] = compiler_path + "clang"
  235. env["CXX"] = compiler_path + "clang++"
  236. env["AR"] = compiler_path + "ar"
  237. env["RANLIB"] = compiler_path + "ranlib"
  238. env["SHLIBSUFFIX"] = ".dylib"
  239. env.Append(CCFLAGS=["-arch", env["ios_arch"], "-isysroot", sdk_path])
  240. env.Append(
  241. LINKFLAGS=[
  242. "-arch",
  243. env["ios_arch"],
  244. "-Wl,-undefined,dynamic_lookup",
  245. "-isysroot",
  246. sdk_path,
  247. "-F" + sdk_path,
  248. ]
  249. )
  250. if env["target"] == "debug":
  251. env.Append(CCFLAGS=["-Og", "-g"])
  252. elif env["target"] == "release":
  253. env.Append(CCFLAGS=["-O3"])
  254. elif env["platform"] == "windows":
  255. if host_platform == "windows" and not env["use_mingw"]:
  256. # MSVC
  257. env.Append(LINKFLAGS=["/WX"])
  258. if env["target"] == "debug":
  259. env.Append(CCFLAGS=["/Z7", "/Od", "/EHsc", "/D_DEBUG", "/MDd"])
  260. elif env["target"] == "release":
  261. env.Append(CCFLAGS=["/O2", "/EHsc", "/DNDEBUG", "/MD"])
  262. elif host_platform == "linux" or host_platform == "freebsd" or host_platform == "osx":
  263. # Cross-compilation using MinGW
  264. if env["bits"] == "64":
  265. env["CXX"] = "x86_64-w64-mingw32-g++"
  266. env["AR"] = "x86_64-w64-mingw32-ar"
  267. env["RANLIB"] = "x86_64-w64-mingw32-ranlib"
  268. env["LINK"] = "x86_64-w64-mingw32-g++"
  269. elif env["bits"] == "32":
  270. env["CXX"] = "i686-w64-mingw32-g++"
  271. env["AR"] = "i686-w64-mingw32-ar"
  272. env["RANLIB"] = "i686-w64-mingw32-ranlib"
  273. env["LINK"] = "i686-w64-mingw32-g++"
  274. elif host_platform == "windows" and env["use_mingw"]:
  275. # Don't Clone the environment. Because otherwise, SCons will pick up msvc stuff.
  276. env = Environment(ENV=os.environ, tools=["mingw"])
  277. opts.Update(env)
  278. # Still need to use C++14.
  279. env.Append(CCFLAGS=["-std=c++14"])
  280. # Don't want lib prefixes
  281. env["IMPLIBPREFIX"] = ""
  282. env["SHLIBPREFIX"] = ""
  283. env["SPAWN"] = mySpawn
  284. env.Replace(ARFLAGS=["q"])
  285. # Native or cross-compilation using MinGW
  286. if host_platform == "linux" or host_platform == "freebsd" or host_platform == "osx" or env["use_mingw"]:
  287. # These options are for a release build even using target=debug
  288. env.Append(CCFLAGS=["-O3", "-Wwrite-strings"])
  289. env.Append(
  290. LINKFLAGS=[
  291. "--static",
  292. "-Wl,--no-undefined",
  293. "-static-libgcc",
  294. "-static-libstdc++",
  295. ]
  296. )
  297. elif env["platform"] == "android":
  298. if host_platform == "windows":
  299. # Don't Clone the environment. Because otherwise, SCons will pick up msvc stuff.
  300. env = Environment(ENV=os.environ, tools=["mingw"])
  301. opts.Update(env)
  302. # Long line hack. Use custom spawn, quick AR append (to avoid files with the same names to override each other).
  303. env["SPAWN"] = mySpawn
  304. env.Replace(ARFLAGS=["q"])
  305. # Verify NDK root
  306. if not "ANDROID_NDK_ROOT" in env:
  307. raise ValueError(
  308. "To build for Android, ANDROID_NDK_ROOT must be defined. Please set ANDROID_NDK_ROOT to the root folder of your Android NDK installation."
  309. )
  310. # Validate API level
  311. api_level = int(env["android_api_level"])
  312. if env["android_arch"] in ["x86_64", "arm64v8"] and api_level < 21:
  313. print("WARN: 64-bit Android architectures require an API level of at least 21; setting android_api_level=21")
  314. env["android_api_level"] = "21"
  315. api_level = 21
  316. # Setup toolchain
  317. toolchain = env["ANDROID_NDK_ROOT"] + "/toolchains/llvm/prebuilt/"
  318. if host_platform == "windows":
  319. toolchain += "windows"
  320. import platform as pltfm
  321. if pltfm.machine().endswith("64"):
  322. toolchain += "-x86_64"
  323. elif host_platform == "linux":
  324. toolchain += "linux-x86_64"
  325. elif host_platform == "osx":
  326. toolchain += "darwin-x86_64"
  327. env.PrependENVPath("PATH", toolchain + "/bin") # This does nothing half of the time, but we'll put it here anyways
  328. # Get architecture info
  329. arch_info_table = {
  330. "armv7": {
  331. "march": "armv7-a",
  332. "target": "armv7a-linux-androideabi",
  333. "tool_path": "arm-linux-androideabi",
  334. "compiler_path": "armv7a-linux-androideabi",
  335. "ccflags": ["-mfpu=neon"],
  336. },
  337. "arm64v8": {
  338. "march": "armv8-a",
  339. "target": "aarch64-linux-android",
  340. "tool_path": "aarch64-linux-android",
  341. "compiler_path": "aarch64-linux-android",
  342. "ccflags": [],
  343. },
  344. "x86": {
  345. "march": "i686",
  346. "target": "i686-linux-android",
  347. "tool_path": "i686-linux-android",
  348. "compiler_path": "i686-linux-android",
  349. "ccflags": ["-mstackrealign"],
  350. },
  351. "x86_64": {
  352. "march": "x86-64",
  353. "target": "x86_64-linux-android",
  354. "tool_path": "x86_64-linux-android",
  355. "compiler_path": "x86_64-linux-android",
  356. "ccflags": [],
  357. },
  358. }
  359. arch_info = arch_info_table[env["android_arch"]]
  360. # Setup tools
  361. env["CC"] = toolchain + "/bin/clang"
  362. env["CXX"] = toolchain + "/bin/clang++"
  363. env["AR"] = toolchain + "/bin/llvm-ar"
  364. env["AS"] = toolchain + "/bin/llvm-as"
  365. env["LD"] = toolchain + "/bin/llvm-ld"
  366. env["STRIP"] = toolchain + "/bin/llvm-strip"
  367. env["RANLIB"] = toolchain + "/bin/llvm-ranlib"
  368. env["SHLIBSUFFIX"] = ".so"
  369. env.Append(
  370. CCFLAGS=[
  371. "--target=" + arch_info["target"] + env["android_api_level"],
  372. "-march=" + arch_info["march"],
  373. "-fPIC",
  374. ]
  375. )
  376. env.Append(CCFLAGS=arch_info["ccflags"])
  377. env.Append(LINKFLAGS=["--target=" + arch_info["target"] + env["android_api_level"], "-march=" + arch_info["march"]])
  378. if env["target"] == "debug":
  379. env.Append(CCFLAGS=["-Og", "-g"])
  380. elif env["target"] == "release":
  381. env.Append(CCFLAGS=["-O3"])
  382. elif env["platform"] == "javascript":
  383. env["ENV"] = os.environ
  384. env["CC"] = "emcc"
  385. env["CXX"] = "em++"
  386. env["AR"] = "emar"
  387. env["RANLIB"] = "emranlib"
  388. env.Append(CPPFLAGS=["-s", "SIDE_MODULE=1"])
  389. env.Append(LINKFLAGS=["-s", "SIDE_MODULE=1"])
  390. env["SHOBJSUFFIX"] = ".bc"
  391. env["SHLIBSUFFIX"] = ".wasm"
  392. # Use TempFileMunge since some AR invocations are too long for cmd.exe.
  393. # Use POSIX-style paths, required with TempFileMunge.
  394. env["ARCOM_POSIX"] = env["ARCOM"].replace("$TARGET", "$TARGET.posix").replace("$SOURCES", "$SOURCES.posix")
  395. env["ARCOM"] = "${TEMPFILE(ARCOM_POSIX)}"
  396. # All intermediate files are just LLVM bitcode.
  397. env["OBJPREFIX"] = ""
  398. env["OBJSUFFIX"] = ".bc"
  399. env["PROGPREFIX"] = ""
  400. # Program() output consists of multiple files, so specify suffixes manually at builder.
  401. env["PROGSUFFIX"] = ""
  402. env["LIBPREFIX"] = "lib"
  403. env["LIBSUFFIX"] = ".a"
  404. env["LIBPREFIXES"] = ["$LIBPREFIX"]
  405. env["LIBSUFFIXES"] = ["$LIBSUFFIX"]
  406. env.Replace(SHLINKFLAGS="$LINKFLAGS")
  407. env.Replace(SHLINKFLAGS="$LINKFLAGS")
  408. if env["target"] == "debug":
  409. env.Append(CCFLAGS=["-O0", "-g"])
  410. elif env["target"] == "release":
  411. env.Append(CCFLAGS=["-O3"])
  412. env.Append(
  413. CPPPATH=[
  414. ".",
  415. env["headers_dir"],
  416. "include",
  417. "include/gen",
  418. "include/core",
  419. ]
  420. )
  421. # Generate bindings?
  422. json_api_file = ""
  423. if "custom_api_file" in env:
  424. json_api_file = env["custom_api_file"]
  425. else:
  426. json_api_file = os.path.join(os.getcwd(), env["headers_dir"], "api.json")
  427. if env["generate_bindings"] == "auto":
  428. # Check if generated files exist
  429. should_generate_bindings = not os.path.isfile(os.path.join(os.getcwd(), "src", "gen", "Object.cpp"))
  430. else:
  431. should_generate_bindings = env["generate_bindings"] in ["yes", "true"]
  432. if should_generate_bindings:
  433. # Actually create the bindings here
  434. import binding_generator
  435. binding_generator.generate_bindings(json_api_file, env["generate_template_get_node"])
  436. # Sources to compile
  437. sources = []
  438. add_sources(sources, "src/core", "cpp")
  439. add_sources(sources, "src/gen", "cpp")
  440. arch_suffix = env["bits"]
  441. if env["platform"] == "android":
  442. arch_suffix = env["android_arch"]
  443. elif env["platform"] == "ios":
  444. arch_suffix = env["ios_arch"]
  445. if env["ios_simulator"]:
  446. arch_suffix += ".simulator"
  447. elif env["platform"] == "osx":
  448. if env["macos_arch"] != "universal":
  449. arch_suffix = env["macos_arch"]
  450. elif env["platform"] == "javascript":
  451. arch_suffix = "wasm"
  452. # Expose it to projects that import this env.
  453. env["arch_suffix"] = arch_suffix
  454. library = None
  455. env["OBJSUFFIX"] = ".{}.{}.{}{}".format(env["platform"], env["target"], arch_suffix, env["OBJSUFFIX"])
  456. library_name = "libgodot-cpp.{}.{}.{}{}".format(env["platform"], env["target"], arch_suffix, env["LIBSUFFIX"])
  457. if env["build_library"]:
  458. library = env.StaticLibrary(target=env.File("bin/%s" % library_name), source=sources)
  459. Default(library)
  460. env.Append(CPPPATH=[env.Dir(f) for f in [env["headers_dir"], "include", "include/gen", "include/core"]])
  461. env.Append(LIBPATH=[env.Dir("bin")])
  462. env.Append(LIBS=library_name)
  463. Return("env")