detect.py 8.4 KB

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