godotcpp.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import os, sys, platform
  2. from SCons.Variables import EnumVariable, PathVariable, BoolVariable
  3. from SCons.Tool import Tool
  4. from SCons.Builder import Builder
  5. from SCons.Errors import UserError
  6. from binding_generator import scons_generate_bindings, scons_emit_files
  7. def add_sources(sources, dir, extension):
  8. for f in os.listdir(dir):
  9. if f.endswith("." + extension):
  10. sources.append(dir + "/" + f)
  11. def normalize_path(val, env):
  12. return val if os.path.isabs(val) else os.path.join(env.Dir("#").abspath, val)
  13. def validate_file(key, val, env):
  14. if not os.path.isfile(normalize_path(val, env)):
  15. raise UserError("'%s' is not a file: %s" % (key, val))
  16. def validate_dir(key, val, env):
  17. if not os.path.isdir(normalize_path(val, env)):
  18. raise UserError("'%s' is not a directory: %s" % (key, val))
  19. def validate_parent_dir(key, val, env):
  20. if not os.path.isdir(normalize_path(os.path.dirname(val), env)):
  21. raise UserError("'%s' is not a directory: %s" % (key, os.path.dirname(val)))
  22. platforms = ("linux", "macos", "windows", "android", "ios", "web")
  23. # CPU architecture options.
  24. architecture_array = [
  25. "",
  26. "universal",
  27. "x86_32",
  28. "x86_64",
  29. "arm32",
  30. "arm64",
  31. "rv64",
  32. "ppc32",
  33. "ppc64",
  34. "wasm32",
  35. ]
  36. architecture_aliases = {
  37. "x64": "x86_64",
  38. "amd64": "x86_64",
  39. "armv7": "arm32",
  40. "armv8": "arm64",
  41. "arm64v8": "arm64",
  42. "aarch64": "arm64",
  43. "rv": "rv64",
  44. "riscv": "rv64",
  45. "riscv64": "rv64",
  46. "ppcle": "ppc32",
  47. "ppc": "ppc32",
  48. "ppc64le": "ppc64",
  49. }
  50. def exists(env):
  51. return True
  52. def options(opts, env):
  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. default_platform = "linux"
  57. elif sys.platform == "darwin":
  58. default_platform = "macos"
  59. elif sys.platform == "win32" or sys.platform == "msys":
  60. default_platform = "windows"
  61. elif ARGUMENTS.get("platform", ""):
  62. default_platform = ARGUMENTS.get("platform")
  63. else:
  64. raise ValueError("Could not detect platform automatically, please specify with platform=<platform>")
  65. opts.Add(
  66. EnumVariable(
  67. key="platform",
  68. help="Target platform",
  69. default=env.get("platform", default_platform),
  70. allowed_values=platforms,
  71. ignorecase=2,
  72. )
  73. )
  74. # Editor and template_debug are compatible (i.e. you can use the same binary for Godot editor builds and Godot debug templates).
  75. # Godot release templates are only compatible with "template_release" builds.
  76. # For this reason, we default to template_debug builds, unlike Godot which defaults to editor builds.
  77. opts.Add(
  78. EnumVariable(
  79. key="target",
  80. help="Compilation target",
  81. default=env.get("target", "template_debug"),
  82. allowed_values=("editor", "template_release", "template_debug"),
  83. )
  84. )
  85. opts.Add(
  86. PathVariable(
  87. key="gdextension_dir",
  88. help="Path to a custom directory containing GDExtension interface header and API JSON file",
  89. default=env.get("gdextension_dir", None),
  90. validator=validate_dir,
  91. )
  92. )
  93. opts.Add(
  94. PathVariable(
  95. key="custom_api_file",
  96. help="Path to a custom GDExtension API JSON file (takes precedence over `gdextension_dir`)",
  97. default=env.get("custom_api_file", None),
  98. validator=validate_file,
  99. )
  100. )
  101. opts.Add(
  102. BoolVariable(
  103. key="generate_bindings",
  104. help="Force GDExtension API bindings generation. Auto-detected by default.",
  105. default=env.get("generate_bindings", False),
  106. )
  107. )
  108. opts.Add(
  109. BoolVariable(
  110. key="generate_template_get_node",
  111. help="Generate a template version of the Node class's get_node.",
  112. default=env.get("generate_template_get_node", True),
  113. )
  114. )
  115. opts.Add(
  116. BoolVariable(
  117. key="build_library",
  118. help="Build the godot-cpp library.",
  119. default=env.get("build_library", True),
  120. )
  121. )
  122. opts.Add(
  123. EnumVariable(
  124. key="precision",
  125. help="Set the floating-point precision level",
  126. default=env.get("precision", "single"),
  127. allowed_values=("single", "double"),
  128. )
  129. )
  130. opts.Add(
  131. EnumVariable(
  132. key="arch",
  133. help="CPU architecture",
  134. default=env.get("arch", ""),
  135. allowed_values=architecture_array,
  136. map=architecture_aliases,
  137. )
  138. )
  139. # compiledb
  140. opts.Add(
  141. BoolVariable(
  142. key="compiledb",
  143. help="Generate compilation DB (`compile_commands.json`) for external tools",
  144. default=env.get("compiledb", False),
  145. )
  146. )
  147. opts.Add(
  148. PathVariable(
  149. key="compiledb_file",
  150. help="Path to a custom `compile_commands.json` file",
  151. default=env.get("compiledb_file", "compile_commands.json"),
  152. validator=validate_parent_dir,
  153. )
  154. )
  155. opts.Add(
  156. BoolVariable(
  157. "disable_exceptions",
  158. "Force disabling exception handling code",
  159. default=env.get("disable_exceptions", False),
  160. )
  161. )
  162. # Add platform options
  163. for pl in platforms:
  164. tool = Tool(pl, toolpath=["tools"])
  165. if hasattr(tool, "options"):
  166. tool.options(opts)
  167. # Targets flags tool (optimizations, debug symbols)
  168. target_tool = Tool("targets", toolpath=["tools"])
  169. target_tool.options(opts)
  170. def generate(env):
  171. # Default num_jobs to local cpu count if not user specified.
  172. # SCons has a peculiarity where user-specified options won't be overridden
  173. # by SetOption, so we can rely on this to know if we should use our default.
  174. initial_num_jobs = env.GetOption("num_jobs")
  175. altered_num_jobs = initial_num_jobs + 1
  176. env.SetOption("num_jobs", altered_num_jobs)
  177. if env.GetOption("num_jobs") == altered_num_jobs:
  178. cpu_count = os.cpu_count()
  179. if cpu_count is None:
  180. print("Couldn't auto-detect CPU count to configure build parallelism. Specify it with the -j argument.")
  181. else:
  182. safer_cpu_count = cpu_count if cpu_count <= 4 else cpu_count - 1
  183. print(
  184. "Auto-detected %d CPU cores available for build parallelism. Using %d cores by default. You can override it with the -j argument."
  185. % (cpu_count, safer_cpu_count)
  186. )
  187. env.SetOption("num_jobs", safer_cpu_count)
  188. # Process CPU architecture argument.
  189. if env["arch"] == "":
  190. # No architecture specified. Default to arm64 if building for Android,
  191. # universal if building for macOS or iOS, wasm32 if building for web,
  192. # otherwise default to the host architecture.
  193. if env["platform"] in ["macos", "ios"]:
  194. env["arch"] = "universal"
  195. elif env["platform"] == "android":
  196. env["arch"] = "arm64"
  197. elif env["platform"] == "web":
  198. env["arch"] = "wasm32"
  199. else:
  200. host_machine = platform.machine().lower()
  201. if host_machine in architecture_array:
  202. env["arch"] = host_machine
  203. elif host_machine in architecture_aliases.keys():
  204. env["arch"] = architecture_aliases[host_machine]
  205. elif "86" in host_machine:
  206. # Catches x86, i386, i486, i586, i686, etc.
  207. env["arch"] = "x86_32"
  208. else:
  209. print("Unsupported CPU architecture: " + host_machine)
  210. env.Exit(1)
  211. print("Building for architecture " + env["arch"] + " on platform " + env["platform"])
  212. tool = Tool(env["platform"], toolpath=["tools"])
  213. if tool is None or not tool.exists(env):
  214. raise ValueError("Required toolchain not found for platform " + env["platform"])
  215. tool.generate(env)
  216. target_tool = Tool("targets", toolpath=["tools"])
  217. target_tool.generate(env)
  218. # Disable exception handling. Godot doesn't use exceptions anywhere, and this
  219. # saves around 20% of binary size and very significant build time.
  220. if env["disable_exceptions"]:
  221. if env.get("is_msvc", False):
  222. env.Append(CPPDEFINES=[("_HAS_EXCEPTIONS", 0)])
  223. else:
  224. env.Append(CXXFLAGS=["-fno-exceptions"])
  225. elif env.get("is_msvc", False):
  226. env.Append(CXXFLAGS=["/EHsc"])
  227. # Require C++17
  228. if env.get("is_msvc", False):
  229. env.Append(CXXFLAGS=["/std:c++17"])
  230. else:
  231. env.Append(CXXFLAGS=["-std=c++17"])
  232. if env["precision"] == "double":
  233. env.Append(CPPDEFINES=["REAL_T_IS_DOUBLE"])
  234. # Suffix
  235. suffix = ".{}.{}".format(env["platform"], env["target"])
  236. if env.dev_build:
  237. suffix += ".dev"
  238. if env["precision"] == "double":
  239. suffix += ".double"
  240. suffix += "." + env["arch"]
  241. if env["ios_simulator"]:
  242. suffix += ".simulator"
  243. env["suffix"] = suffix # Exposed when included from another project
  244. env["OBJSUFFIX"] = suffix + env["OBJSUFFIX"]
  245. # compile_commands.json
  246. env.Tool("compilation_db")
  247. env.Alias("compiledb", env.CompilationDatabase(normalize_path(env["compiledb_file"], env)))
  248. # Builders
  249. env.Append(BUILDERS={"GodotCPPBindings": Builder(action=scons_generate_bindings, emitter=scons_emit_files)})
  250. env.AddMethod(_godot_cpp, "GodotCPP")
  251. def _godot_cpp(env):
  252. extension_dir = normalize_path(env.get("gdextension_dir", env.Dir("gdextension").abspath), env)
  253. api_file = normalize_path(env.get("custom_api_file", env.File(extension_dir + "/extension_api.json").abspath), env)
  254. bindings = env.GodotCPPBindings(
  255. env.Dir("."),
  256. [
  257. api_file,
  258. os.path.join(extension_dir, "gdextension_interface.h"),
  259. "binding_generator.py",
  260. ],
  261. )
  262. # Forces bindings regeneration.
  263. if env["generate_bindings"]:
  264. env.AlwaysBuild(bindings)
  265. env.NoCache(bindings)
  266. # Sources to compile
  267. sources = []
  268. add_sources(sources, "src", "cpp")
  269. add_sources(sources, "src/classes", "cpp")
  270. add_sources(sources, "src/core", "cpp")
  271. add_sources(sources, "src/variant", "cpp")
  272. sources.extend([f for f in bindings if str(f).endswith(".cpp")])
  273. # Includes
  274. env.AppendUnique(CPPPATH=[env.Dir(d) for d in [extension_dir, "include", "gen/include"]])
  275. library = None
  276. library_name = "libgodot-cpp" + env["suffix"] + env["LIBSUFFIX"]
  277. if env["build_library"]:
  278. library = env.StaticLibrary(target=env.File("bin/%s" % library_name), source=sources)
  279. default_args = [library]
  280. # Add compiledb if the option is set
  281. if env.get("compiledb", False):
  282. default_args += ["compiledb"]
  283. env.Default(*default_args)
  284. env.AppendUnique(LIBS=[env.File("bin/%s" % library_name)])
  285. return library