SConstruct 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. #!/usr/bin/env python
  2. import os
  3. import platform
  4. import sys
  5. import subprocess
  6. from binding_generator import scons_generate_bindings, scons_emit_files
  7. from SCons.Errors import UserError
  8. EnsureSConsVersion(4, 0)
  9. def add_sources(sources, dir, extension):
  10. for f in os.listdir(dir):
  11. if f.endswith("." + extension):
  12. sources.append(dir + "/" + f)
  13. def normalize_path(val):
  14. return val if os.path.isabs(val) else os.path.join(env.Dir("#").abspath, val)
  15. def validate_api_file(key, val, env):
  16. if not os.path.isfile(normalize_path(val)):
  17. raise UserError("GDExtension API file ('%s') does not exist: %s" % (key, val))
  18. def validate_gdextension_dir(key, val, env):
  19. if not os.path.isdir(normalize_path(val)):
  20. raise UserError("GDExtension directory ('%s') does not exist: %s" % (key, val))
  21. def get_gdextension_dir(env):
  22. return normalize_path(env.get("gdextension_dir", env.Dir("gdextension").abspath))
  23. def get_api_file(env):
  24. return normalize_path(env.get("custom_api_file", os.path.join(get_gdextension_dir(env), "extension_api.json")))
  25. # Try to detect the host platform automatically.
  26. # This is used if no `platform` argument is passed
  27. if sys.platform.startswith("linux"):
  28. default_platform = "linux"
  29. elif sys.platform == "darwin":
  30. default_platform = "macos"
  31. elif sys.platform == "win32" or sys.platform == "msys":
  32. default_platform = "windows"
  33. elif ARGUMENTS.get("platform", ""):
  34. default_platform = ARGUMENTS.get("platform")
  35. else:
  36. raise ValueError("Could not detect platform automatically, please specify with platform=<platform>")
  37. # Default tools with no platform defaults to gnu toolchain.
  38. # We apply platform specific toolchains via our custom tools.
  39. env = Environment(tools=["default"], PLATFORM="")
  40. env.PrependENVPath("PATH", os.getenv("PATH"))
  41. # Default num_jobs to local cpu count if not user specified.
  42. # SCons has a peculiarity where user-specified options won't be overridden
  43. # by SetOption, so we can rely on this to know if we should use our default.
  44. initial_num_jobs = env.GetOption("num_jobs")
  45. altered_num_jobs = initial_num_jobs + 1
  46. env.SetOption("num_jobs", altered_num_jobs)
  47. if env.GetOption("num_jobs") == altered_num_jobs:
  48. cpu_count = os.cpu_count()
  49. if cpu_count is None:
  50. print("Couldn't auto-detect CPU count to configure build parallelism. Specify it with the -j argument.")
  51. else:
  52. safer_cpu_count = cpu_count if cpu_count <= 4 else cpu_count - 1
  53. print(
  54. "Auto-detected %d CPU cores available for build parallelism. Using %d cores by default. You can override it with the -j argument."
  55. % (cpu_count, safer_cpu_count)
  56. )
  57. env.SetOption("num_jobs", safer_cpu_count)
  58. # Custom options and profile flags.
  59. customs = ["custom.py"]
  60. profile = ARGUMENTS.get("profile", "")
  61. if profile:
  62. if os.path.isfile(profile):
  63. customs.append(profile)
  64. elif os.path.isfile(profile + ".py"):
  65. customs.append(profile + ".py")
  66. opts = Variables(customs, ARGUMENTS)
  67. platforms = ("linux", "macos", "windows", "android", "ios", "javascript")
  68. opts.Add(
  69. EnumVariable(
  70. "platform",
  71. "Target platform",
  72. default_platform,
  73. allowed_values=platforms,
  74. ignorecase=2,
  75. )
  76. )
  77. # Editor and template_debug are compatible (i.e. you can use the same binary for Godot editor builds and Godot debug templates).
  78. # Godot release templates are only compatible with "template_release" builds.
  79. # For this reason, we default to template_debug builds, unlike Godot which defaults to editor builds.
  80. opts.Add(
  81. EnumVariable("target", "Compilation target", "template_debug", ("editor", "template_release", "template_debug"))
  82. )
  83. opts.Add(
  84. PathVariable(
  85. "gdextension_dir",
  86. "Path to a custom directory containing GDExtension interface header and API JSON file",
  87. None,
  88. validate_gdextension_dir,
  89. )
  90. )
  91. opts.Add(
  92. PathVariable(
  93. "custom_api_file",
  94. "Path to a custom GDExtension API JSON file (takes precedence over `gdextension_dir`)",
  95. None,
  96. validate_api_file,
  97. )
  98. )
  99. opts.Add(
  100. BoolVariable("generate_bindings", "Force GDExtension API bindings generation. Auto-detected by default.", False)
  101. )
  102. opts.Add(BoolVariable("generate_template_get_node", "Generate a template version of the Node class's get_node.", True))
  103. opts.Add(BoolVariable("build_library", "Build the godot-cpp library.", True))
  104. opts.Add(EnumVariable("precision", "Set the floating-point precision level", "single", ("single", "double")))
  105. # Add platform options
  106. tools = {}
  107. for pl in platforms:
  108. tool = Tool(pl, toolpath=["tools"])
  109. if hasattr(tool, "options"):
  110. tool.options(opts)
  111. tools[pl] = tool
  112. # CPU architecture options.
  113. architecture_array = ["", "universal", "x86_32", "x86_64", "arm32", "arm64", "rv64", "ppc32", "ppc64", "wasm32"]
  114. architecture_aliases = {
  115. "x64": "x86_64",
  116. "amd64": "x86_64",
  117. "armv7": "arm32",
  118. "armv8": "arm64",
  119. "arm64v8": "arm64",
  120. "aarch64": "arm64",
  121. "rv": "rv64",
  122. "riscv": "rv64",
  123. "riscv64": "rv64",
  124. "ppcle": "ppc32",
  125. "ppc": "ppc32",
  126. "ppc64le": "ppc64",
  127. }
  128. opts.Add(EnumVariable("arch", "CPU architecture", "", architecture_array, architecture_aliases))
  129. # Targets flags tool (optimizations, debug symbols)
  130. target_tool = Tool("targets", toolpath=["tools"])
  131. target_tool.options(opts)
  132. opts.Update(env)
  133. Help(opts.GenerateHelpText(env))
  134. # Process CPU architecture argument.
  135. if env["arch"] == "":
  136. # No architecture specified. Default to arm64 if building for Android,
  137. # universal if building for macOS or iOS, wasm32 if building for web,
  138. # otherwise default to the host architecture.
  139. if env["platform"] in ["macos", "ios"]:
  140. env["arch"] = "universal"
  141. elif env["platform"] == "android":
  142. env["arch"] = "arm64"
  143. elif env["platform"] == "javascript":
  144. env["arch"] = "wasm32"
  145. else:
  146. host_machine = platform.machine().lower()
  147. if host_machine in architecture_array:
  148. env["arch"] = host_machine
  149. elif host_machine in architecture_aliases.keys():
  150. env["arch"] = architecture_aliases[host_machine]
  151. elif "86" in host_machine:
  152. # Catches x86, i386, i486, i586, i686, etc.
  153. env["arch"] = "x86_32"
  154. else:
  155. print("Unsupported CPU architecture: " + host_machine)
  156. Exit()
  157. tool = Tool(env["platform"], toolpath=["tools"])
  158. if tool is None or not tool.exists(env):
  159. raise ValueError("Required toolchain not found for platform " + env["platform"])
  160. tool.generate(env)
  161. target_tool.generate(env)
  162. # Detect and print a warning listing unknown SCons variables to ease troubleshooting.
  163. unknown = opts.UnknownVariables()
  164. if unknown:
  165. print("WARNING: Unknown SCons variables were passed and will be ignored:")
  166. for item in unknown.items():
  167. print(" " + item[0] + "=" + item[1])
  168. print("Building for architecture " + env["arch"] + " on platform " + env["platform"])
  169. # Require C++17
  170. if env.get("is_msvc", False):
  171. env.Append(CXXFLAGS=["/std:c++17"])
  172. else:
  173. env.Append(CXXFLAGS=["-std=c++17"])
  174. if env["precision"] == "double":
  175. env.Append(CPPDEFINES=["REAL_T_IS_DOUBLE"])
  176. # Generate bindings
  177. env.Append(BUILDERS={"GenerateBindings": Builder(action=scons_generate_bindings, emitter=scons_emit_files)})
  178. bindings = env.GenerateBindings(
  179. env.Dir("."),
  180. [get_api_file(env), os.path.join(get_gdextension_dir(env), "gdextension_interface.h"), "binding_generator.py"],
  181. )
  182. scons_cache_path = os.environ.get("SCONS_CACHE")
  183. if scons_cache_path is not None:
  184. CacheDir(scons_cache_path)
  185. Decider("MD5")
  186. # Forces bindings regeneration.
  187. if env["generate_bindings"]:
  188. AlwaysBuild(bindings)
  189. NoCache(bindings)
  190. # Includes
  191. env.Append(CPPPATH=[[env.Dir(d) for d in [get_gdextension_dir(env), "include", os.path.join("gen", "include")]]])
  192. # Sources to compile
  193. sources = []
  194. add_sources(sources, "src", "cpp")
  195. add_sources(sources, "src/classes", "cpp")
  196. add_sources(sources, "src/core", "cpp")
  197. add_sources(sources, "src/variant", "cpp")
  198. sources.extend([f for f in bindings if str(f).endswith(".cpp")])
  199. suffix = ".{}.{}".format(env["platform"], env["target"])
  200. if env.dev_build:
  201. suffix += ".dev"
  202. if env["precision"] == "double":
  203. suffix += ".double"
  204. suffix += "." + env["arch"]
  205. if env["ios_simulator"]:
  206. suffix += ".simulator"
  207. # Expose it when included from another project
  208. env["suffix"] = suffix
  209. library = None
  210. env["OBJSUFFIX"] = suffix + env["OBJSUFFIX"]
  211. library_name = "libgodot-cpp{}{}".format(suffix, env["LIBSUFFIX"])
  212. if env["build_library"]:
  213. library = env.StaticLibrary(target=env.File("bin/%s" % library_name), source=sources)
  214. Default(library)
  215. env.Append(LIBPATH=[env.Dir("bin")])
  216. env.Append(LIBS=library_name)
  217. Return("env")