godotcpp.py 20 KB

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