godotcpp.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. import os
  2. import platform
  3. import sys
  4. from SCons.Action import Action
  5. from SCons.Builder import Builder
  6. from SCons.Errors import UserError
  7. from SCons.Script import ARGUMENTS
  8. from SCons.Tool import Tool
  9. from SCons.Variables import BoolVariable, EnumVariable, PathVariable
  10. from SCons.Variables.BoolVariable import _text2bool
  11. from binding_generator import scons_emit_files, scons_generate_bindings
  12. def add_sources(sources, dir, extension):
  13. for f in os.listdir(dir):
  14. if f.endswith("." + extension):
  15. sources.append(dir + "/" + f)
  16. def get_cmdline_bool(option, default):
  17. """We use `ARGUMENTS.get()` to check if options were manually overridden on the command line,
  18. and SCons' _text2bool helper to convert them to booleans, otherwise they're handled as strings.
  19. """
  20. cmdline_val = ARGUMENTS.get(option)
  21. if cmdline_val is not None:
  22. return _text2bool(cmdline_val)
  23. else:
  24. return default
  25. def normalize_path(val, env):
  26. return val if os.path.isabs(val) else os.path.join(env.Dir("#").abspath, val)
  27. def validate_file(key, val, env):
  28. if not os.path.isfile(normalize_path(val, env)):
  29. raise UserError("'%s' is not a file: %s" % (key, val))
  30. def validate_dir(key, val, env):
  31. if not os.path.isdir(normalize_path(val, env)):
  32. raise UserError("'%s' is not a directory: %s" % (key, val))
  33. def validate_parent_dir(key, val, env):
  34. if not os.path.isdir(normalize_path(os.path.dirname(val), env)):
  35. raise UserError("'%s' is not a directory: %s" % (key, os.path.dirname(val)))
  36. def get_platform_tools_paths(env):
  37. path = env.get("custom_tools", None)
  38. if path is None:
  39. return ["tools"]
  40. return [normalize_path(path, env), "tools"]
  41. def get_custom_platforms(env):
  42. path = env.get("custom_tools", None)
  43. if path is None:
  44. return []
  45. platforms = []
  46. for x in os.listdir(normalize_path(path, env)):
  47. if not x.endswith(".py"):
  48. continue
  49. platforms.append(x.removesuffix(".py"))
  50. return platforms
  51. def no_verbose(env):
  52. colors = {}
  53. # Colors are disabled in non-TTY environments such as pipes. This means
  54. # that if output is redirected to a file, it will not contain color codes
  55. if sys.stdout.isatty():
  56. colors["blue"] = "\033[0;94m"
  57. colors["bold_blue"] = "\033[1;94m"
  58. colors["reset"] = "\033[0m"
  59. else:
  60. colors["blue"] = ""
  61. colors["bold_blue"] = ""
  62. colors["reset"] = ""
  63. # There is a space before "..." to ensure that source file names can be
  64. # Ctrl + clicked in the VS Code terminal.
  65. compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(
  66. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  67. )
  68. java_compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(
  69. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  70. )
  71. compile_shared_source_message = "{}Compiling shared {}$SOURCE{} ...{}".format(
  72. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  73. )
  74. link_program_message = "{}Linking Program {}$TARGET{} ...{}".format(
  75. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  76. )
  77. link_library_message = "{}Linking Static Library {}$TARGET{} ...{}".format(
  78. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  79. )
  80. ranlib_library_message = "{}Ranlib Library {}$TARGET{} ...{}".format(
  81. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  82. )
  83. link_shared_library_message = "{}Linking Shared Library {}$TARGET{} ...{}".format(
  84. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  85. )
  86. java_library_message = "{}Creating Java Archive {}$TARGET{} ...{}".format(
  87. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  88. )
  89. compiled_resource_message = "{}Creating Compiled Resource {}$TARGET{} ...{}".format(
  90. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  91. )
  92. generated_file_message = "{}Generating {}$TARGET{} ...{}".format(
  93. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  94. )
  95. env.Append(CXXCOMSTR=[compile_source_message])
  96. env.Append(CCCOMSTR=[compile_source_message])
  97. env.Append(SHCCCOMSTR=[compile_shared_source_message])
  98. env.Append(SHCXXCOMSTR=[compile_shared_source_message])
  99. env.Append(ARCOMSTR=[link_library_message])
  100. env.Append(RANLIBCOMSTR=[ranlib_library_message])
  101. env.Append(SHLINKCOMSTR=[link_shared_library_message])
  102. env.Append(LINKCOMSTR=[link_program_message])
  103. env.Append(JARCOMSTR=[java_library_message])
  104. env.Append(JAVACCOMSTR=[java_compile_source_message])
  105. env.Append(RCCOMSTR=[compiled_resource_message])
  106. env.Append(GENCOMSTR=[generated_file_message])
  107. platforms = ["linux", "macos", "windows", "android", "ios", "web"]
  108. # CPU architecture options.
  109. architecture_array = [
  110. "",
  111. "universal",
  112. "x86_32",
  113. "x86_64",
  114. "arm32",
  115. "arm64",
  116. "rv64",
  117. "ppc32",
  118. "ppc64",
  119. "wasm32",
  120. ]
  121. architecture_aliases = {
  122. "x64": "x86_64",
  123. "amd64": "x86_64",
  124. "armv7": "arm32",
  125. "armv8": "arm64",
  126. "arm64v8": "arm64",
  127. "aarch64": "arm64",
  128. "rv": "rv64",
  129. "riscv": "rv64",
  130. "riscv64": "rv64",
  131. "ppcle": "ppc32",
  132. "ppc": "ppc32",
  133. "ppc64le": "ppc64",
  134. }
  135. def exists(env):
  136. return True
  137. def options(opts, env):
  138. # Try to detect the host platform automatically.
  139. # This is used if no `platform` argument is passed
  140. if sys.platform.startswith("linux"):
  141. default_platform = "linux"
  142. elif sys.platform == "darwin":
  143. default_platform = "macos"
  144. elif sys.platform == "win32" or sys.platform == "msys":
  145. default_platform = "windows"
  146. elif ARGUMENTS.get("platform", ""):
  147. default_platform = ARGUMENTS.get("platform")
  148. else:
  149. raise ValueError("Could not detect platform automatically, please specify with platform=<platform>")
  150. opts.Add(
  151. PathVariable(
  152. key="custom_tools",
  153. help="Path to directory containing custom tools",
  154. default=env.get("custom_tools", None),
  155. validator=validate_dir,
  156. )
  157. )
  158. opts.Update(env)
  159. custom_platforms = get_custom_platforms(env)
  160. opts.Add(
  161. EnumVariable(
  162. key="platform",
  163. help="Target platform",
  164. default=env.get("platform", default_platform),
  165. allowed_values=platforms + custom_platforms,
  166. ignorecase=2,
  167. )
  168. )
  169. # Editor and template_debug are compatible (i.e. you can use the same binary for Godot editor builds and Godot debug templates).
  170. # Godot release templates are only compatible with "template_release" builds.
  171. # For this reason, we default to template_debug builds, unlike Godot which defaults to editor builds.
  172. opts.Add(
  173. EnumVariable(
  174. key="target",
  175. help="Compilation target",
  176. default=env.get("target", "template_debug"),
  177. allowed_values=("editor", "template_release", "template_debug"),
  178. )
  179. )
  180. opts.Add(
  181. PathVariable(
  182. key="gdextension_dir",
  183. help="Path to a custom directory containing GDExtension interface header and API JSON file",
  184. default=env.get("gdextension_dir", None),
  185. validator=validate_dir,
  186. )
  187. )
  188. opts.Add(
  189. PathVariable(
  190. key="custom_api_file",
  191. help="Path to a custom GDExtension API JSON file (takes precedence over `gdextension_dir`)",
  192. default=env.get("custom_api_file", None),
  193. validator=validate_file,
  194. )
  195. )
  196. opts.Add(
  197. BoolVariable(
  198. key="generate_bindings",
  199. help="Force GDExtension API bindings generation. Auto-detected by default.",
  200. default=env.get("generate_bindings", False),
  201. )
  202. )
  203. opts.Add(
  204. BoolVariable(
  205. key="generate_template_get_node",
  206. help="Generate a template version of the Node class's get_node.",
  207. default=env.get("generate_template_get_node", True),
  208. )
  209. )
  210. opts.Add(
  211. BoolVariable(
  212. key="build_library",
  213. help="Build the godot-cpp library.",
  214. default=env.get("build_library", True),
  215. )
  216. )
  217. opts.Add(
  218. EnumVariable(
  219. key="precision",
  220. help="Set the floating-point precision level",
  221. default=env.get("precision", "single"),
  222. allowed_values=("single", "double"),
  223. )
  224. )
  225. opts.Add(
  226. EnumVariable(
  227. key="arch",
  228. help="CPU architecture",
  229. default=env.get("arch", ""),
  230. allowed_values=architecture_array,
  231. map=architecture_aliases,
  232. )
  233. )
  234. # compiledb
  235. opts.Add(
  236. BoolVariable(
  237. key="compiledb",
  238. help="Generate compilation DB (`compile_commands.json`) for external tools",
  239. default=env.get("compiledb", False),
  240. )
  241. )
  242. opts.Add(
  243. PathVariable(
  244. key="compiledb_file",
  245. help="Path to a custom `compile_commands.json` file",
  246. default=env.get("compiledb_file", "compile_commands.json"),
  247. validator=validate_parent_dir,
  248. )
  249. )
  250. opts.Add(
  251. PathVariable(
  252. "build_profile",
  253. "Path to a file containing a feature build profile",
  254. default=env.get("build_profile", None),
  255. validator=validate_file,
  256. )
  257. )
  258. opts.Add(
  259. BoolVariable(
  260. "disable_exceptions",
  261. "Force disabling exception handling code",
  262. default=env.get("disable_exceptions", False),
  263. )
  264. )
  265. opts.Add(
  266. EnumVariable(
  267. key="symbols_visibility",
  268. help="Symbols visibility on GNU platforms. Use 'auto' to apply the default value.",
  269. default=env.get("symbols_visibility", "hidden"),
  270. allowed_values=["auto", "visible", "hidden"],
  271. )
  272. )
  273. opts.Add(
  274. EnumVariable(
  275. "optimize",
  276. "The desired optimization flags",
  277. "speed_trace",
  278. ("none", "custom", "debug", "speed", "speed_trace", "size"),
  279. )
  280. )
  281. opts.Add(BoolVariable("debug_symbols", "Build with debugging symbols", True))
  282. opts.Add(BoolVariable("dev_build", "Developer build with dev-only debugging code (DEV_ENABLED)", False))
  283. opts.Add(BoolVariable("verbose", "Enable verbose output for the compilation", False))
  284. # Add platform options (custom tools can override platforms)
  285. for pl in sorted(set(platforms + custom_platforms)):
  286. tool = Tool(pl, toolpath=get_platform_tools_paths(env))
  287. if hasattr(tool, "options"):
  288. tool.options(opts)
  289. def generate(env):
  290. # Default num_jobs to local cpu count if not user specified.
  291. # SCons has a peculiarity where user-specified options won't be overridden
  292. # by SetOption, so we can rely on this to know if we should use our default.
  293. initial_num_jobs = env.GetOption("num_jobs")
  294. altered_num_jobs = initial_num_jobs + 1
  295. env.SetOption("num_jobs", altered_num_jobs)
  296. if env.GetOption("num_jobs") == altered_num_jobs:
  297. cpu_count = os.cpu_count()
  298. if cpu_count is None:
  299. print("Couldn't auto-detect CPU count to configure build parallelism. Specify it with the -j argument.")
  300. else:
  301. safer_cpu_count = cpu_count if cpu_count <= 4 else cpu_count - 1
  302. print(
  303. "Auto-detected %d CPU cores available for build parallelism. Using %d cores by default. You can override it with the -j argument."
  304. % (cpu_count, safer_cpu_count)
  305. )
  306. env.SetOption("num_jobs", safer_cpu_count)
  307. # Process CPU architecture argument.
  308. if env["arch"] == "":
  309. # No architecture specified. Default to arm64 if building for Android,
  310. # universal if building for macOS or iOS, wasm32 if building for web,
  311. # otherwise default to the host architecture.
  312. if env["platform"] in ["macos", "ios"]:
  313. env["arch"] = "universal"
  314. elif env["platform"] == "android":
  315. env["arch"] = "arm64"
  316. elif env["platform"] == "web":
  317. env["arch"] = "wasm32"
  318. else:
  319. host_machine = platform.machine().lower()
  320. if host_machine in architecture_array:
  321. env["arch"] = host_machine
  322. elif host_machine in architecture_aliases.keys():
  323. env["arch"] = architecture_aliases[host_machine]
  324. elif "86" in host_machine:
  325. # Catches x86, i386, i486, i586, i686, etc.
  326. env["arch"] = "x86_32"
  327. else:
  328. print("Unsupported CPU architecture: " + host_machine)
  329. env.Exit(1)
  330. print("Building for architecture " + env["arch"] + " on platform " + env["platform"])
  331. # These defaults may be needed by platform tools
  332. env.editor_build = env["target"] == "editor"
  333. env.dev_build = env["dev_build"]
  334. env.debug_features = env["target"] in ["editor", "template_debug"]
  335. if env.dev_build:
  336. opt_level = "none"
  337. elif env.debug_features:
  338. opt_level = "speed_trace"
  339. else: # Release
  340. opt_level = "speed"
  341. env["optimize"] = ARGUMENTS.get("optimize", opt_level)
  342. env["debug_symbols"] = get_cmdline_bool("debug_symbols", env.dev_build)
  343. tool = Tool(env["platform"], toolpath=get_platform_tools_paths(env))
  344. if tool is None or not tool.exists(env):
  345. raise ValueError("Required toolchain not found for platform " + env["platform"])
  346. tool.generate(env)
  347. if env.editor_build:
  348. env.Append(CPPDEFINES=["TOOLS_ENABLED"])
  349. # Configuration of build targets:
  350. # - Editor or template
  351. # - Debug features (DEBUG_ENABLED code)
  352. # - Dev only code (DEV_ENABLED code)
  353. # - Optimization level
  354. # - Debug symbols for crash traces / debuggers
  355. # Keep this configuration in sync with SConstruct in upstream Godot.
  356. if env.debug_features:
  357. # DEBUG_ENABLED enables debugging *features* and debug-only code, which is intended
  358. # to give *users* extra debugging information for their game development.
  359. env.Append(CPPDEFINES=["DEBUG_ENABLED"])
  360. # In upstream Godot this is added in typedefs.h when DEBUG_ENABLED is set.
  361. env.Append(CPPDEFINES=["DEBUG_METHODS_ENABLED"])
  362. if env.dev_build:
  363. # DEV_ENABLED enables *engine developer* code which should only be compiled for those
  364. # working on the engine itself.
  365. env.Append(CPPDEFINES=["DEV_ENABLED"])
  366. else:
  367. # Disable assert() for production targets (only used in thirdparty code).
  368. env.Append(CPPDEFINES=["NDEBUG"])
  369. if env["precision"] == "double":
  370. env.Append(CPPDEFINES=["REAL_T_IS_DOUBLE"])
  371. # Allow detecting when building as a GDExtension.
  372. env.Append(CPPDEFINES=["GDEXTENSION"])
  373. # Suffix
  374. suffix = ".{}.{}".format(env["platform"], env["target"])
  375. if env.dev_build:
  376. suffix += ".dev"
  377. if env["precision"] == "double":
  378. suffix += ".double"
  379. suffix += "." + env["arch"]
  380. if env["ios_simulator"]:
  381. suffix += ".simulator"
  382. env["suffix"] = suffix # Exposed when included from another project
  383. env["OBJSUFFIX"] = suffix + env["OBJSUFFIX"]
  384. # compile_commands.json
  385. env.Tool("compilation_db")
  386. env.Alias("compiledb", env.CompilationDatabase(normalize_path(env["compiledb_file"], env)))
  387. # Formatting
  388. if not env["verbose"]:
  389. no_verbose(env)
  390. # Builders
  391. env.Append(
  392. BUILDERS={
  393. "GodotCPPBindings": Builder(action=Action(scons_generate_bindings, "$GENCOMSTR"), emitter=scons_emit_files)
  394. }
  395. )
  396. env.AddMethod(_godot_cpp, "GodotCPP")
  397. def _godot_cpp(env):
  398. extension_dir = normalize_path(env.get("gdextension_dir", env.Dir("gdextension").abspath), env)
  399. api_file = normalize_path(env.get("custom_api_file", env.File(extension_dir + "/extension_api.json").abspath), env)
  400. bindings = env.GodotCPPBindings(
  401. env.Dir("."),
  402. [
  403. api_file,
  404. os.path.join(extension_dir, "gdextension_interface.h"),
  405. "binding_generator.py",
  406. ],
  407. )
  408. # Forces bindings regeneration.
  409. if env["generate_bindings"]:
  410. env.AlwaysBuild(bindings)
  411. env.NoCache(bindings)
  412. # Sources to compile
  413. sources = []
  414. add_sources(sources, "src", "cpp")
  415. add_sources(sources, "src/classes", "cpp")
  416. add_sources(sources, "src/core", "cpp")
  417. add_sources(sources, "src/variant", "cpp")
  418. sources.extend([f for f in bindings if str(f).endswith(".cpp")])
  419. # Includes
  420. env.AppendUnique(CPPPATH=[env.Dir(d) for d in [extension_dir, "include", "gen/include"]])
  421. library = None
  422. library_name = "libgodot-cpp" + env["suffix"] + env["LIBSUFFIX"]
  423. if env["build_library"]:
  424. library = env.StaticLibrary(target=env.File("bin/%s" % library_name), source=sources)
  425. default_args = [library]
  426. # Add compiledb if the option is set
  427. if env.get("compiledb", False):
  428. default_args += ["compiledb"]
  429. env.Default(*default_args)
  430. env.AppendUnique(LIBS=[env.File("bin/%s" % library_name)])
  431. return library