华佗热更新模块

AssetBudleTool.cs 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. #if HybridCLR
  2. using HybridCLR.Editor.Commands;
  3. using HybridCLR.Editor;
  4. #endif
  5. using Newtonsoft.Json;
  6. using System;
  7. using System.Collections;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Security.Cryptography;
  11. using System.Text;
  12. using TFramework;
  13. using TModule.Runtime;
  14. using UnityEditor;
  15. using UnityEngine;
  16. namespace TModule.Editor
  17. {
  18. public class AssetBudleTool : EditorWindow
  19. {
  20. private string AssetBudleConfigName = "AssetBundleConfig.asset";
  21. private string AssetBudleConfigPath;
  22. private string AssetbudleToolConfigName = "BudleToolConfig.asset";
  23. private string AssetbudleToolConfigPath;
  24. private AssetBudleConfig _list;
  25. private AssetBudleConfig BudleConfig
  26. {
  27. get
  28. {
  29. _list = _list ?? AssetDatabase.LoadAssetAtPath<AssetBudleConfig>(AssetBudleConfigPath);
  30. if (_list == null)
  31. {
  32. _list = CreateInstance<AssetBudleConfig>();
  33. AssetDatabase.CreateAsset(_list, AssetBudleConfigPath);
  34. }
  35. return _list;
  36. }
  37. set => _list = value;
  38. }
  39. private AssetBudleToolConfig _toolConfig;
  40. private AssetBudleToolConfig BudleToolConfig
  41. {
  42. get
  43. {
  44. _toolConfig = _toolConfig ?? AssetDatabase.LoadAssetAtPath<AssetBudleToolConfig>(AssetbudleToolConfigPath);
  45. if (_toolConfig == null)
  46. {
  47. _toolConfig = CreateInstance<AssetBudleToolConfig>();
  48. AssetDatabase.CreateAsset(_toolConfig, AssetbudleToolConfigPath);
  49. }
  50. return _toolConfig;
  51. }
  52. set => _toolConfig = value;
  53. }
  54. private static List<VersionDataEntity> versionDatas = new List<VersionDataEntity>();
  55. private Vector2 _scorllView = Vector2.zero;
  56. #if UNITY_STANDALONE_WIN
  57. private BuildTarget _buildTarget = BuildTarget.StandaloneWindows64;
  58. #elif UNITY_ANDROID
  59. private BuildTarget _buildTarget = BuildTarget.Android;
  60. #elif UNITY_IPHON
  61. private BuildTarget _buildTarget = BuildTarget.iOS;
  62. #endif
  63. [MenuItem("TModule/热更/AssetBudleTool")]
  64. public static void OpenWin()
  65. {
  66. AssetBudleTool win = GetWindow<AssetBudleTool>();
  67. win.maxSize = new Vector2(800, 400);
  68. win.titleContent.text = "ABTool";
  69. win.titleContent.image = EditorGUIUtility.IconContent("PrefabModel Icon").image;
  70. win.Show();
  71. }
  72. private void OnEnable()
  73. {
  74. var ms = MonoScript.FromScriptableObject(this);
  75. var path = AssetDatabase.GetAssetPath(ms);
  76. path = Path.GetDirectoryName(path);
  77. AssetBudleConfigPath = Path.Combine(path, AssetBudleConfigName);
  78. AssetbudleToolConfigPath = Path.Combine(path, AssetbudleToolConfigName);
  79. }
  80. private void OnGUI()
  81. {
  82. using (new EditorGUILayout.HorizontalScope("Box"))
  83. {
  84. EditorGUILayout.LabelField("打包平台:", GUILayout.Width(60));
  85. _buildTarget = (BuildTarget)EditorGUILayout.EnumPopup(_buildTarget);
  86. EditorGUILayout.LabelField("输出路径:", GUILayout.Width(60));
  87. BudleToolConfig.m_savePath = EditorGUILayout.TextField(BudleToolConfig.m_savePath);
  88. if (GUILayout.Button(EditorGUIUtility.IconContent("Project@2x").image, GUILayout.Height(20), GUILayout.Width(40)))
  89. {
  90. try
  91. {
  92. BudleToolConfig.m_savePath = EditorUtility.OpenFolderPanel("AB包输出路径", "Assets", "Assets");
  93. }
  94. catch (Exception e)
  95. {
  96. Debug.Log(e.Message);
  97. }
  98. }
  99. }
  100. float _width = position.width / 6;
  101. using (new EditorGUILayout.HorizontalScope("Box"))
  102. {
  103. EditorGUILayout.LabelField("包名", GUILayout.Width(_width * 4));
  104. EditorGUILayout.LabelField("文件夹", GUILayout.Width(_width));
  105. EditorGUILayout.LabelField("操作");
  106. }
  107. _scorllView = EditorGUILayout.BeginScrollView(_scorllView);
  108. for (int i = 0; i < BudleConfig.m_AB.Count; i++)
  109. {
  110. using (new EditorGUILayout.HorizontalScope())
  111. {
  112. BudleConfig.m_AB[i].m_name = EditorGUILayout.TextField(BudleConfig.m_AB[i].m_name, GUILayout.Width(_width * 4));
  113. BudleConfig.m_AB[i].m_isFolder = EditorGUILayout.Toggle(BudleConfig.m_AB[i].m_isFolder, GUILayout.Width(_width));
  114. if (GUILayout.Button(EditorGUIUtility.IconContent("TreeEditor.Trash").image, GUILayout.Height(20)))
  115. {
  116. BudleConfig.m_AB.Remove(BudleConfig.m_AB[i]);
  117. }
  118. }
  119. }
  120. if (GUILayout.Button(EditorGUIUtility.IconContent("CreateAddNew@2x").image, GUILayout.Height(30), GUILayout.Width(30)))
  121. {
  122. BudleConfig.m_AB.Add(new AssetBundleEntity());
  123. }
  124. EditorGUILayout.EndScrollView();
  125. if (GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition))
  126. {
  127. if (Event.current.type == EventType.DragUpdated)
  128. DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
  129. else if (Event.current.type == EventType.DragExited)
  130. {
  131. if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0)
  132. {
  133. for (int i = 0; i < DragAndDrop.paths.Length; i++)
  134. {
  135. if (BudleConfig.m_AB.Find(p => p.m_name == DragAndDrop.paths[i]) == null)
  136. BudleConfig.m_AB.Add(new AssetBundleEntity()
  137. { m_name = DragAndDrop.paths[i] });
  138. }
  139. }
  140. }
  141. }
  142. using (new EditorGUILayout.HorizontalScope())
  143. {
  144. EditorGUILayout.LabelField("将打包资源拷贝到StreamingAssets文件夹", GUILayout.Width(230));
  145. BudleToolConfig.m_copyToStreamingAssets = EditorGUILayout.Toggle(BudleToolConfig.m_copyToStreamingAssets);
  146. }
  147. if (GUILayout.Button("构建AssetBundle"))
  148. {
  149. OnAssetBundleCallBack();
  150. }
  151. }
  152. /// <summary>
  153. /// 打包回调
  154. /// </summary>
  155. private void OnAssetBundleCallBack()
  156. {
  157. string tartgetPath = BudleToolConfig.m_savePath + "/" + _buildTarget.ToString();
  158. if (!Directory.Exists(tartgetPath))
  159. Directory.CreateDirectory(tartgetPath);
  160. SetABName();
  161. BuildPipeline.BuildAssetBundles(tartgetPath, BuildAssetBundleOptions.None, _buildTarget);
  162. #if HybridCLR
  163. CompileDllCommand.CompileDll(_buildTarget);
  164. CopyAOTAssembliesToPath(tartgetPath);
  165. CopyHotUpdateAssembliesToPath(tartgetPath);
  166. #endif
  167. if (BudleToolConfig.m_copyToStreamingAssets)
  168. CopyToStreamingAssets();
  169. OnCreateVersionText();
  170. AssetDatabase.Refresh();
  171. }
  172. private void SetABName()
  173. {
  174. for (int i = 0; i < BudleConfig.m_AB.Count; i++)
  175. {
  176. AssetBundleEntity assetBudle = BudleConfig.m_AB[i];
  177. if (assetBudle.m_isFolder)
  178. {
  179. string[] floderArr = new string[] { GetAbsolutePath(assetBudle.m_name) };
  180. SaveFolderSettings(floderArr);
  181. }
  182. else
  183. {
  184. SaveFileSettings(Application.dataPath + "/" + assetBudle.m_name);
  185. }
  186. }
  187. }
  188. private void SaveFolderSettings(string[] folderArr)
  189. {
  190. foreach (string floderPath in folderArr)
  191. {
  192. string[] arrFile = Directory.GetFiles(floderPath);
  193. foreach (string filePah in arrFile)
  194. {
  195. SaveFileSettings(filePah);
  196. }
  197. string[] arrFolder = Directory.GetDirectories(floderPath);
  198. SaveFolderSettings(arrFolder);
  199. }
  200. }
  201. private void SaveFileSettings(string filePath)
  202. {
  203. FileInfo file = new FileInfo(filePath);
  204. if (!file.Extension.Equals(".meta", StringComparison.CurrentCultureIgnoreCase))
  205. {
  206. int index = filePath.IndexOf("Assets/", StringComparison.CurrentCultureIgnoreCase);
  207. string newPath = filePath.Substring(index);
  208. string fileName = newPath.Substring(newPath.IndexOf("Assets/")).Replace(file.Extension, "");
  209. string variant = file.Extension.Equals(".unity", StringComparison.CurrentCultureIgnoreCase) ? "unity3d" : "assetbundle";
  210. AssetImporter importer = AssetImporter.GetAtPath(newPath);
  211. if (importer.assetBundleName == "None" || string.IsNullOrEmpty(importer.assetBundleName))
  212. {
  213. importer.SetAssetBundleNameAndVariant(fileName, variant);
  214. importer.SaveAndReimport();
  215. }
  216. }
  217. }
  218. private void CopyToStreamingAssets()
  219. {
  220. string toPath = Application.streamingAssetsPath;
  221. string tartgetPath = BudleToolConfig.m_savePath + "/" + _buildTarget.ToString();
  222. CopyDirectory(tartgetPath, toPath, true);
  223. AssetDatabase.Refresh();
  224. }
  225. /// <summary>
  226. /// 创建版本文件
  227. /// </summary>
  228. private void OnCreateVersionText()
  229. {
  230. string strVersionJsonPath = $"{BudleToolConfig.m_savePath}/{_buildTarget.ToString()}/VersionFile.json";
  231. versionDatas.Clear();
  232. if (File.Exists(strVersionJsonPath))
  233. File.Delete(strVersionJsonPath);
  234. StringBuilder sbContent = new StringBuilder();
  235. DirectoryInfo directory = new DirectoryInfo(BudleToolConfig.m_savePath);
  236. FileInfo[] arrfiles = directory.GetFiles("*", SearchOption.AllDirectories);
  237. for (int i = 0; i < arrfiles.Length; i++)
  238. {
  239. FileInfo file = arrfiles[i];
  240. string fullName = file.FullName;
  241. string md5 = GetFileMD5(fullName);
  242. if (md5 == null) continue;
  243. string subPath = $"{BudleToolConfig.m_savePath}/{_buildTarget.ToString()}";
  244. versionDatas.Add(new VersionDataEntity()
  245. {
  246. m_fullName = fullName.Substring(fullName.IndexOf(subPath) + subPath.Length + 2),
  247. m_md5 = md5,
  248. m_size = Mathf.Ceil(file.Length / 1024.0f)
  249. });
  250. }
  251. WriteJsonData(versionDatas, strVersionJsonPath);
  252. }
  253. private void OnDisable()
  254. {
  255. EditorUtility.SetDirty(_list);
  256. EditorUtility.SetDirty(BudleToolConfig);
  257. AssetDatabase.SaveAssets();
  258. }
  259. public string GetAbsolutePath(string path)
  260. {
  261. string _path = Application.dataPath.Remove(Application.dataPath.LastIndexOf('/') + 1);
  262. return _path + path;
  263. }
  264. /// <summary>
  265. /// 拷贝文件夹
  266. /// </summary>
  267. /// <param name="sourceDirName"></param>
  268. /// <param name="destDirName"></param>
  269. /// <param name="isOverlay">是否覆盖已有同名文件</param>
  270. public void CopyDirectory(string sourceDirName, string destDirName, bool isOverlay = false)
  271. {
  272. try
  273. {
  274. if (!Directory.Exists(destDirName))
  275. {
  276. Directory.CreateDirectory(destDirName);
  277. File.SetAttributes(destDirName, File.GetAttributes(sourceDirName));
  278. }
  279. if (destDirName[destDirName.Length - 1] != Path.DirectorySeparatorChar)
  280. destDirName = destDirName + Path.DirectorySeparatorChar;
  281. string[] files = Directory.GetFiles(sourceDirName);
  282. foreach (string file in files)
  283. {
  284. if (File.Exists(destDirName + Path.GetFileName(file)) && !isOverlay)
  285. continue;
  286. FileInfo fileInfo = new FileInfo(file);
  287. if (fileInfo.Extension.Equals(".meta", StringComparison.CurrentCultureIgnoreCase))
  288. continue;
  289. File.Copy(file, destDirName + Path.GetFileName(file), true);
  290. File.SetAttributes(destDirName + Path.GetFileName(file), FileAttributes.Normal);
  291. }
  292. string[] dirs = Directory.GetDirectories(sourceDirName);
  293. foreach (string dir in dirs)
  294. {
  295. CopyDirectory(dir, destDirName + Path.GetFileName(dir), isOverlay);
  296. }
  297. }
  298. catch (Exception ex)
  299. {
  300. throw ex;
  301. }
  302. }
  303. /// <summary>
  304. /// 写入数据
  305. /// </summary>
  306. /// <param name="data">数据</param>
  307. /// <param name="path">文件完整路径</param>
  308. public static void WriteJsonData(object data, string path)
  309. {
  310. string json = JsonConvert.SerializeObject(data);
  311. using (StreamWriter sw = new StreamWriter(path))
  312. {
  313. //保存数据
  314. sw.WriteLine(json);
  315. //关闭文档
  316. sw.Close();
  317. sw.Dispose();
  318. }
  319. }
  320. /// <summary>
  321. /// 获取文件MD5
  322. /// </summary>
  323. /// <param name="filePath"></param>
  324. /// <returns></returns>
  325. public static string GetFileMD5(string filePath)
  326. {
  327. if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
  328. return null;
  329. try
  330. {
  331. FileStream file = new FileStream(filePath, FileMode.Open);
  332. MD5 mD5 = new MD5CryptoServiceProvider();
  333. byte[] byteResult = mD5.ComputeHash(file);
  334. string strResult = BitConverter.ToString(byteResult);
  335. strResult = strResult.Replace("-", "");
  336. return strResult;
  337. }
  338. catch
  339. {
  340. return null;
  341. }
  342. }
  343. #if HybridCLR
  344. public void CopyAOTAssembliesToPath(string path)
  345. {
  346. string aotAssembliesSrcDir = SettingsUtil.GetAssembliesPostIl2CppStripDir(_buildTarget);
  347. foreach (var dll in Resources.Load<HotfixConfig>("HotfixUpdate/热更配置表").m_hotfixUpdateAotDlls)
  348. {
  349. string srcDllPath = $"{aotAssembliesSrcDir}/{dll}";
  350. if (!File.Exists(srcDllPath))
  351. {
  352. Log.Error($"ab中添加AOT补充元数据dll:{srcDllPath} 时发生错误,文件不存在。裁剪后的AOT dll在BuildPlayer时才能生成,因此需要你先构建一次游戏App后再打包。");
  353. continue;
  354. }
  355. string dllBytesPath = $"{path}/{dll}.bytes";
  356. File.Copy(srcDllPath, dllBytesPath, true);
  357. Log.Info($"【CopyAOTAssemblies】 copy AOT dll {srcDllPath} -> {dllBytesPath}");
  358. }
  359. }
  360. public static void CopyHotUpdateAssembliesToPath(string path)
  361. {
  362. var target = EditorUserBuildSettings.activeBuildTarget;
  363. string hotfixDllSrcDir = SettingsUtil.GetHotUpdateDllsOutputDirByTarget(target);
  364. string hotfixAssembliesDstDir = Application.streamingAssetsPath;
  365. foreach (var dll in SettingsUtil.HotUpdateAssemblyFilesExcludePreserved)
  366. {
  367. string dllPath = $"{hotfixDllSrcDir}/{dll}";
  368. string dllBytesPath = $"{path}/{dll}.bytes";
  369. File.Copy(dllPath, dllBytesPath, true);
  370. Log.Info($"【CopyHotUpdateAssemblies】 copy hotfix dll {dllPath} -> {dllBytesPath}");
  371. }
  372. AssetDatabase.Refresh();
  373. }
  374. #endif
  375. }
  376. }