godotcpp.py 10 KB

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