PreprocessBuildBase.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. /****************************************************************************
  2. * Copyright 2019 Nreal Techonology Limited. All rights reserved.
  3. *
  4. * This file is part of NRSDK.
  5. *
  6. * https://www.nreal.ai/
  7. *
  8. *****************************************************************************/
  9. namespace NRKernal
  10. {
  11. using System.Diagnostics.CodeAnalysis;
  12. using System.Xml;
  13. using UnityEditor;
  14. using UnityEditor.Build;
  15. using System.IO;
  16. #if UNITY_2018_1_OR_NEWER
  17. using UnityEditor.Build.Reporting;
  18. using UnityEngine;
  19. using UnityEditor.Android;
  20. using System.Text;
  21. using System.Text.RegularExpressions;
  22. #endif
  23. #if UNITY_2018_1_OR_NEWER
  24. /// <summary> The preprocess build base. </summary>
  25. internal class PreprocessBuildBase : IPreprocessBuildWithReport
  26. #else
  27. internal class PreprocessBuildBase : IPreprocessBuild
  28. #endif
  29. {
  30. /// <summary>
  31. /// <para>Returns the relative callback order for callbacks. Callbacks with lower values are
  32. /// called before ones with higher values.</para> </summary>
  33. /// <value> The callback order. </value>
  34. public int callbackOrder
  35. {
  36. get
  37. {
  38. return 0;
  39. }
  40. }
  41. #if UNITY_2018_1_OR_NEWER
  42. /// <summary>
  43. /// <para>Implement this function to receive a callback before the build is started.</para> </summary>
  44. /// <param name="report"> A report containing information about the build, such as its target
  45. /// platform and output path.</param>
  46. public void OnPreprocessBuild(BuildReport report)
  47. {
  48. OnPreprocessBuild(report.summary.platform, report.summary.outputPath);
  49. }
  50. #endif
  51. /// <summary> Executes the 'preprocess build' action. </summary>
  52. /// <param name="target"> Target for the.</param>
  53. /// <param name="path"> Full pathname of the file.</param>
  54. public virtual void OnPreprocessBuild(BuildTarget target, string path)
  55. {
  56. if (target == BuildTarget.Android)
  57. {
  58. OnPreprocessBuildForAndroid();
  59. }
  60. }
  61. private const string DefaultXML = @"<?xml version='1.0' encoding='utf-8'?>
  62. <manifest
  63. xmlns:android='http://schemas.android.com/apk/res/android'
  64. package='com.unity3d.player'
  65. xmlns:tools='http://schemas.android.com/tools'
  66. android:installLocation='preferExternal'>
  67. <uses-sdk tools:overrideLibrary='com.nreal.glasses_sdk'/>
  68. <supports-screens
  69. android:smallScreens='true'
  70. android:normalScreens='true'
  71. android:largeScreens='true'
  72. android:xlargeScreens='true'
  73. android:anyDensity='true'/>
  74. <application
  75. android:theme='@style/UnityThemeSelector'
  76. android:icon='@mipmap/app_icon'
  77. android:label='@string/app_name'>
  78. <activity android:name='com.unity3d.player.UnityPlayerActivity'>
  79. <intent-filter>
  80. <action android:name='android.intent.action.MAIN' />
  81. <category android:name='android.intent.category.INFO' tools:node='replace'/>
  82. </intent-filter>
  83. </activity>
  84. <meta-data android:name='nreal_sdk' android:value='true'/>
  85. <meta-data android:name='com.nreal.supportDevices' android:value=''/>
  86. </application>
  87. <uses-permission android:name='android.permission.BLUETOOTH'/>
  88. </manifest>
  89. ";
  90. /// <summary> True if is show on desktop, false if not. </summary>
  91. private const bool isShowOnDesktop = true;
  92. /// <summary> Executes the 'preprocess build for android' action. </summary>
  93. [MenuItem("NRSDK/PreprocessBuildForAndroid")]
  94. public static void OnPreprocessBuildForAndroid()
  95. {
  96. string basePath = Application.dataPath + "/Plugins/Android";
  97. if (!Directory.Exists(Application.dataPath + "/Plugins"))
  98. {
  99. Directory.CreateDirectory(Application.dataPath + "/Plugins");
  100. }
  101. if (!Directory.Exists(basePath))
  102. {
  103. Directory.CreateDirectory(basePath);
  104. }
  105. string xmlPath = Application.dataPath + "/Plugins/Android/AndroidManifest.xml";
  106. if (!File.Exists(xmlPath))
  107. {
  108. string xml = DefaultXML.Replace("\'", "\"");
  109. if (isShowOnDesktop)
  110. {
  111. xml = xml.Replace("<category android:name=\"android.intent.category.INFO\" tools:node=\"replace\"/>",
  112. "<category android:name=\"android.intent.category.LAUNCHER\" />");
  113. }
  114. File.WriteAllText(xmlPath, xml);
  115. }
  116. AutoGenerateAndroidManifest(xmlPath);
  117. ApplySettingsToConfig();
  118. AutoGenerateAndroidGradleTemplate();
  119. AssetDatabase.Refresh();
  120. }
  121. private static void ApplySettingsToConfig()
  122. {
  123. NRProjectConfig projectConfig = NRProjectConfigHelper.GetProjectConfig();
  124. var sessionConfigGuids = AssetDatabase.FindAssets("t:NRSessionConfig");
  125. foreach (var item in sessionConfigGuids)
  126. {
  127. var config = AssetDatabase.LoadAssetAtPath<NRSessionConfig>(
  128. AssetDatabase.GUIDToAssetPath(item));
  129. config.SetUseMultiThread(PlayerSettings.GetMobileMTRendering(BuildTargetGroup.Android));
  130. config.SetProjectConfig(projectConfig);
  131. EditorUtility.SetDirty(config);
  132. }
  133. AssetDatabase.SaveAssets();
  134. AssetDatabase.Refresh();
  135. }
  136. [MenuItem("NRSDK/AddAudioPermission")]
  137. public static void AddAudioPermission()
  138. {
  139. string xmlPath = Application.dataPath + "/Plugins/Android/AndroidManifest.xml";
  140. var androidManifest = new AndroidManifest(xmlPath);
  141. androidManifest.SetAudioRecordPermission();
  142. androidManifest.Save();
  143. }
  144. [MenuItem("NRSDK/InitVideoPlayerDemoEnv")]
  145. public static void InitVideoPlayerDemoEnv()
  146. {
  147. string javaDir = "";
  148. string[] assets = AssetDatabase.FindAssets("AndroidMediaPlayer");
  149. foreach (var asset in assets)
  150. {
  151. string path = AssetDatabase.GUIDToAssetPath(asset);
  152. if (path.Contains("NRSDKExperimental") && path.EndsWith(".java"))
  153. {
  154. javaDir = Path.GetDirectoryName(path);
  155. break;
  156. }
  157. }
  158. if (!string.IsNullOrEmpty(javaDir))
  159. {
  160. string[] files = Directory.GetFiles(javaDir, "*.java");
  161. foreach (var file in files)
  162. {
  163. PluginImporter importer = (PluginImporter)AssetImporter.GetAtPath(file);
  164. if (importer != null)
  165. {
  166. importer.SetCompatibleWithPlatform(BuildTarget.Android, true);
  167. importer.SaveAndReimport();
  168. }
  169. }
  170. }
  171. //set project dependency
  172. string gradleFile = "mainTemplate.gradle";
  173. if (UseCustomGradleFile(gradleFile))
  174. {
  175. string gradleInProject = Application.dataPath + "/Plugins/Android/" + gradleFile;
  176. AndroidGradleTemplate gradleTmp = new AndroidGradleTemplate(gradleInProject);
  177. gradleTmp.AddDenpendency("implementation 'com.google.android.exoplayer:exoplayer:2.13.2'");
  178. gradleTmp.PreprocessGradleFile();
  179. }
  180. EditorUtility.DisplayDialog("Tips", "Added ExoPlayer library dependency. The scene Overlay-VideoPlayer now supports DRM video playback.", "OK");
  181. }
  182. /// <summary> Automatic generate android manifest. </summary>
  183. /// <param name="path"> Full pathname of the file.</param>
  184. public static void AutoGenerateAndroidManifest(string path)
  185. {
  186. var androidManifest = new AndroidManifest(path);
  187. //bool needrequestLegacyExternalStorage = (GetAndroidTargetApiLevel() >= 29);
  188. //androidManifest.SetExternalStorage(needrequestLegacyExternalStorage);
  189. // androidManifest.SetPackageReadPermission();
  190. //androidManifest.SetCameraPermission();
  191. androidManifest.SetBlueToothPermission();
  192. androidManifest.SetSDKMetaData();
  193. androidManifest.SetAPKDisplayedOnLauncher(isShowOnDesktop);
  194. androidManifest.Save();
  195. }
  196. public static int GetAndroidTargetApiLevel()
  197. {
  198. if (PlayerSettings.Android.targetSdkVersion == AndroidSdkVersions.AndroidApiLevelAuto)
  199. {
  200. string androidsdkRoot = EditorPrefs.GetString("AndroidSdkRoot");
  201. string[] androidVersions = Directory.GetDirectories(Path.Combine(androidsdkRoot, "platforms"));
  202. string regex = "android-([0-9]*)";
  203. int maxVersion = (int)AndroidSdkVersions.AndroidApiLevelAuto;
  204. foreach (var item in androidVersions)
  205. {
  206. MatchCollection coll = Regex.Matches(item, regex);
  207. if (coll != null && coll[0] != null && coll[0].Groups[1] != null)
  208. {
  209. string result = coll[0].Groups[1].Value;
  210. int versionCode = int.Parse(result);
  211. if (versionCode > maxVersion)
  212. {
  213. maxVersion = versionCode;
  214. }
  215. }
  216. }
  217. return maxVersion;
  218. }
  219. else
  220. {
  221. return (int)PlayerSettings.Android.targetSdkVersion;
  222. }
  223. }
  224. /// In order to support 'queries' in manifest, gradle plugin must be higher than 3.4.3.
  225. /// For unity version lower than 2020, this can be modified by using 'Custom Gradle Template', then modify the gradle plugin version in template file
  226. public static void AutoGenerateAndroidGradleTemplate()
  227. {
  228. string version = Application.unityVersion;
  229. Debug.Log("UnityVersion: " + version);
  230. string vMain = version.Substring(0, 4);
  231. int nVersion = 0;
  232. int.TryParse(vMain, out nVersion);
  233. if (nVersion < 2018)
  234. Debug.LogErrorFormat("NRSDK require unity version higher than 2018");
  235. else if (nVersion == 2018)
  236. AutoGenerateAndroidGradleTemplate("mainTemplate.gradle");
  237. else
  238. AutoGenerateAndroidGradleTemplate("baseProjectTemplate.gradle");
  239. //unity2020 should add support android.useAndroidX manually
  240. if (nVersion >= 2020)
  241. {
  242. AutoGenerateGradleProperties("gradleTemplate.properties");
  243. }
  244. }
  245. /// <summary>
  246. /// Use custom gradle file, copy from unity install directory to project directory.
  247. /// </summary>
  248. /// <param name="templateFileName"> gradle file name. </param>
  249. private static bool UseCustomGradleFile(string templateFileName)
  250. {
  251. string gradleInProject = Application.dataPath + "/Plugins/Android/" + templateFileName;
  252. if (!File.Exists(gradleInProject))
  253. {
  254. string unityEditorPath = EditorApplication.applicationPath;
  255. string gradleReletPath = "/PlaybackEngines/AndroidPlayer/Tools/GradleTemplates/" + templateFileName;
  256. #if UNITY_EDITOR_WIN
  257. gradleReletPath = "/data" + gradleReletPath;
  258. #endif
  259. string gradleFullPath = unityEditorPath.Substring(0, unityEditorPath.LastIndexOf("/")) + gradleReletPath;
  260. Debug.LogFormat("Copy gradle template : {0} --> {1}", gradleFullPath, gradleInProject);
  261. if (File.Exists(gradleFullPath))
  262. File.Copy(gradleFullPath, gradleInProject);
  263. else
  264. {
  265. Debug.LogErrorFormat("GradleTemplate of unity not found : {0}", gradleFullPath);
  266. return false;
  267. }
  268. }
  269. return true;
  270. }
  271. /// <summary>
  272. /// Generate custom gradle file, set minal
  273. /// </summary>
  274. /// <param name="templateFileName"> Gradle file name. </param>
  275. private static void AutoGenerateAndroidGradleTemplate(string templateFileName)
  276. {
  277. if(!UseCustomGradleFile(templateFileName))
  278. {
  279. return;
  280. }
  281. string gradleInProject = Application.dataPath + "/Plugins/Android/" + templateFileName;
  282. AndroidGradleTemplate gradleTmp = new AndroidGradleTemplate(gradleInProject);
  283. gradleTmp.SetMinPluginVersion(3, 4, 3);
  284. gradleTmp.PreprocessGradleFile();
  285. }
  286. private static void AutoGenerateGradleProperties(string templateFileName)
  287. {
  288. if (!UseCustomGradleFile(templateFileName))
  289. {
  290. return;
  291. }
  292. string gradleInProject = Application.dataPath + "/Plugins/Android/" + templateFileName;
  293. AndroidGradleTemplate gradleTmp = new AndroidGradleTemplate(gradleInProject);
  294. gradleTmp.AddSupport("android.useAndroidX");
  295. gradleTmp.PreprocessGradleFile();
  296. }
  297. }
  298. }