godotcpp.py 19 KB

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