detect.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. import os
  2. import platform
  3. import subprocess
  4. import sys
  5. from typing import TYPE_CHECKING
  6. from methods import print_error, print_warning
  7. from platform_methods import validate_arch
  8. if TYPE_CHECKING:
  9. from SCons.Script.SConscript import SConsEnvironment
  10. def get_name():
  11. return "Android"
  12. def can_build():
  13. return os.path.exists(get_env_android_sdk_root())
  14. def get_tools(env: "SConsEnvironment"):
  15. return ["clang", "clang++", "as", "ar", "link"]
  16. def get_opts():
  17. from SCons.Variables import BoolVariable
  18. return [
  19. ("ANDROID_HOME", "Path to the Android SDK", get_env_android_sdk_root()),
  20. (
  21. "ndk_platform",
  22. 'Target platform (android-<api>, e.g. "android-' + str(get_min_target_api()) + '")',
  23. "android-" + str(get_min_target_api()),
  24. ),
  25. BoolVariable("store_release", "Editor build for Google Play Store (for official builds only)", False),
  26. BoolVariable("generate_apk", "Generate an APK/AAB after building Android library by calling Gradle", False),
  27. BoolVariable("swappy", "Use Swappy Frame Pacing library", False),
  28. ]
  29. def get_doc_classes():
  30. return [
  31. "EditorExportPlatformAndroid",
  32. ]
  33. def get_doc_path():
  34. return "doc_classes"
  35. # Return the ANDROID_HOME environment variable.
  36. def get_env_android_sdk_root():
  37. return os.environ.get("ANDROID_HOME", os.environ.get("ANDROID_SDK_ROOT", ""))
  38. def get_min_sdk_version(platform):
  39. return int(platform.split("-")[1])
  40. def get_android_ndk_root(env: "SConsEnvironment"):
  41. return env["ANDROID_HOME"] + "/ndk/" + get_ndk_version()
  42. # This is kept in sync with the value in 'platform/android/java/app/config.gradle'.
  43. def get_ndk_version():
  44. return "23.2.8568313"
  45. # This is kept in sync with the value in 'platform/android/java/app/config.gradle'.
  46. def get_min_target_api():
  47. return 21
  48. def get_flags():
  49. return {
  50. "arch": "arm64",
  51. "target": "template_debug",
  52. "supported": ["mono"],
  53. }
  54. # Check if Android NDK version is installed
  55. # If not, install it.
  56. def install_ndk_if_needed(env: "SConsEnvironment"):
  57. sdk_root = env["ANDROID_HOME"]
  58. if not os.path.exists(get_android_ndk_root(env)):
  59. extension = ".bat" if os.name == "nt" else ""
  60. sdkmanager = sdk_root + "/cmdline-tools/latest/bin/sdkmanager" + extension
  61. if os.path.exists(sdkmanager):
  62. # Install the Android NDK
  63. print("Installing Android NDK...")
  64. ndk_download_args = "ndk;" + get_ndk_version()
  65. subprocess.check_call([sdkmanager, ndk_download_args])
  66. else:
  67. print_error(
  68. f'Cannot find "{sdkmanager}". Please ensure ANDROID_HOME is correct and cmdline-tools'
  69. f' are installed, or install NDK version "{get_ndk_version()}" manually.'
  70. )
  71. sys.exit(255)
  72. env["ANDROID_NDK_ROOT"] = get_android_ndk_root(env)
  73. def detect_swappy():
  74. archs = ["arm64-v8a", "armeabi-v7a", "x86", "x86_64"]
  75. has_swappy = True
  76. for arch in archs:
  77. if not os.path.isfile(f"thirdparty/swappy-frame-pacing/{arch}/libswappy_static.a"):
  78. has_swappy = False
  79. return has_swappy
  80. def configure(env: "SConsEnvironment"):
  81. # Validate arch.
  82. supported_arches = ["x86_32", "x86_64", "arm32", "arm64"]
  83. validate_arch(env["arch"], get_name(), supported_arches)
  84. if get_min_sdk_version(env["ndk_platform"]) < get_min_target_api():
  85. print_warning(
  86. "Minimum supported Android target api is %d. Forcing target api %d."
  87. % (get_min_target_api(), get_min_target_api())
  88. )
  89. env["ndk_platform"] = "android-" + str(get_min_target_api())
  90. install_ndk_if_needed(env)
  91. ndk_root = env["ANDROID_NDK_ROOT"]
  92. # Architecture
  93. if env["arch"] == "arm32":
  94. target_triple = "armv7a-linux-androideabi"
  95. elif env["arch"] == "arm64":
  96. target_triple = "aarch64-linux-android"
  97. elif env["arch"] == "x86_32":
  98. target_triple = "i686-linux-android"
  99. elif env["arch"] == "x86_64":
  100. target_triple = "x86_64-linux-android"
  101. target_option = ["-target", target_triple + str(get_min_sdk_version(env["ndk_platform"]))]
  102. env.Append(ASFLAGS=[target_option, "-c"])
  103. env.Append(CCFLAGS=target_option)
  104. env.Append(LINKFLAGS=target_option)
  105. # LTO
  106. if env["lto"] == "auto": # LTO benefits for Android (size, performance) haven't been clearly established yet.
  107. env["lto"] = "none"
  108. if env["lto"] != "none":
  109. if env["lto"] == "thin":
  110. env.Append(CCFLAGS=["-flto=thin"])
  111. env.Append(LINKFLAGS=["-flto=thin"])
  112. else:
  113. env.Append(CCFLAGS=["-flto"])
  114. env.Append(LINKFLAGS=["-flto"])
  115. # Compiler configuration
  116. env["SHLIBSUFFIX"] = ".so"
  117. if env["PLATFORM"] == "win32":
  118. env.use_windows_spawn_fix()
  119. if sys.platform.startswith("linux"):
  120. host_subpath = "linux-x86_64"
  121. elif sys.platform.startswith("darwin"):
  122. host_subpath = "darwin-x86_64"
  123. elif sys.platform.startswith("win"):
  124. if platform.machine().endswith("64"):
  125. host_subpath = "windows-x86_64"
  126. else:
  127. host_subpath = "windows"
  128. toolchain_path = ndk_root + "/toolchains/llvm/prebuilt/" + host_subpath
  129. compiler_path = toolchain_path + "/bin"
  130. env["CC"] = compiler_path + "/clang"
  131. env["CXX"] = compiler_path + "/clang++"
  132. env["AR"] = compiler_path + "/llvm-ar"
  133. env["RANLIB"] = compiler_path + "/llvm-ranlib"
  134. env["AS"] = compiler_path + "/clang"
  135. env.Append(
  136. CCFLAGS=(["-fpic", "-ffunction-sections", "-funwind-tables", "-fstack-protector-strong", "-fvisibility=hidden"])
  137. )
  138. has_swappy = detect_swappy()
  139. if not has_swappy:
  140. print_warning(
  141. "Swappy Frame Pacing not detected! It is strongly recommended you download it from https://github.com/darksylinc/godot-swappy/releases and extract it so that the following files can be found:\n"
  142. + " thirdparty/swappy-frame-pacing/arm64-v8a/libswappy_static.a\n"
  143. + " thirdparty/swappy-frame-pacing/armeabi-v7a/libswappy_static.a\n"
  144. + " thirdparty/swappy-frame-pacing/x86/libswappy_static.a\n"
  145. + " thirdparty/swappy-frame-pacing/x86_64/libswappy_static.a\n"
  146. + "Without Swappy, Godot apps on Android will inevitable suffer stutter and struggle to keep consistent 30/60/90/120 fps. Though Swappy cannot guarantee your app will be stutter-free, not having Swappy will guarantee there will be stutter even on the best phones and the most simple of scenes."
  147. )
  148. if env["swappy"]:
  149. print_error("Use build option `swappy=no` to ignore missing Swappy dependency and build without it.")
  150. sys.exit(255)
  151. if get_min_sdk_version(env["ndk_platform"]) >= 24:
  152. env.Append(CPPDEFINES=[("_FILE_OFFSET_BITS", 64)])
  153. if env["arch"] == "x86_32":
  154. # The NDK adds this if targeting API < 24, so we can drop it when Godot targets it at least
  155. env.Append(CCFLAGS=["-mstackrealign"])
  156. if has_swappy:
  157. env.Append(LIBPATH=["#thirdparty/swappy-frame-pacing/x86"])
  158. elif env["arch"] == "x86_64":
  159. if has_swappy:
  160. env.Append(LIBPATH=["#thirdparty/swappy-frame-pacing/x86_64"])
  161. elif env["arch"] == "arm32":
  162. env.Append(CCFLAGS=["-march=armv7-a", "-mfloat-abi=softfp"])
  163. env.Append(CPPDEFINES=["__ARM_ARCH_7__", "__ARM_ARCH_7A__"])
  164. env.Append(CPPDEFINES=["__ARM_NEON__"])
  165. if has_swappy:
  166. env.Append(LIBPATH=["#thirdparty/swappy-frame-pacing/armeabi-v7a"])
  167. elif env["arch"] == "arm64":
  168. env.Append(CCFLAGS=["-mfix-cortex-a53-835769"])
  169. env.Append(CPPDEFINES=["__ARM_ARCH_8A__"])
  170. if has_swappy:
  171. env.Append(LIBPATH=["#thirdparty/swappy-frame-pacing/arm64-v8a"])
  172. env.Append(CCFLAGS=["-ffp-contract=off"])
  173. # Link flags
  174. env.Append(LINKFLAGS=["-Wl,--gc-sections", "-Wl,--no-undefined", "-Wl,-z,now"])
  175. env.Append(LINKFLAGS=["-Wl,-soname,libgodot_android.so"])
  176. env.Prepend(CPPPATH=["#platform/android"])
  177. env.Append(CPPDEFINES=["ANDROID_ENABLED", "UNIX_ENABLED"])
  178. env.Append(LIBS=["OpenSLES", "EGL", "android", "log", "z", "dl"])
  179. if env["vulkan"]:
  180. env.Append(CPPDEFINES=["VULKAN_ENABLED", "RD_ENABLED"])
  181. if has_swappy:
  182. env.Append(CPPDEFINES=["SWAPPY_FRAME_PACING_ENABLED"])
  183. env.Append(LIBS=["swappy_static"])
  184. if not env["use_volk"]:
  185. env.Append(LIBS=["vulkan"])
  186. if env["opengl3"]:
  187. env.Append(CPPDEFINES=["GLES3_ENABLED"])
  188. env.Append(LIBS=["GLESv3"])