华佗热更新模块

AssetBudleTool.cs 16KB

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