godotcpp.py 19 KB

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