BuildTask.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using GFGEditor;
  5. using GFGGame;
  6. using UnityEditor;
  7. using UnityEngine;
  8. namespace VEngine.Editor.Builds
  9. {
  10. public class BuildTask
  11. {
  12. private readonly string[] EXCLUDE_EXTS = new string[] { ".meta", ".bat" };
  13. private readonly string[] EXCLUDE_DIRS = new string[] { "Assets/Res/.svn", ImportArtResTool.Md5FilePath };
  14. private readonly BuildAssetBundleOptions buildAssetBundleOptions;
  15. private readonly List<Asset> bundledAssets = new List<Asset>();
  16. private readonly string bundleExtension;
  17. public readonly string name;
  18. private readonly Dictionary<string, Asset> pathWithAssets = new Dictionary<string, Asset>();
  19. public BuildTask()
  20. {
  21. name = nameof(Manifest);
  22. buildAssetBundleOptions = BuildAssetBundleOptions.ChunkBasedCompression |
  23. BuildAssetBundleOptions.AppendHashToAssetBundleName;
  24. bundleExtension = ".unity3d";
  25. }
  26. public Record record { get; private set; }
  27. private static string GetRecordsPath(string buildName)
  28. {
  29. return Settings.GetBuildPath($"build_records_for_{buildName}.json");
  30. }
  31. private static void WriteRecord(Record record)
  32. {
  33. var records = GetRecords(record.build);
  34. records.data.Insert(0, record);
  35. File.WriteAllText(GetRecordsPath(record.build), JsonUtility.ToJson(records));
  36. }
  37. private static Records GetRecords(string build)
  38. {
  39. var records = ScriptableObject.CreateInstance<Records>();
  40. var path = GetRecordsPath(build);
  41. if (File.Exists(path)) JsonUtility.FromJsonOverwrite(File.ReadAllText(path), records);
  42. return records;
  43. }
  44. private static void DisplayProgressBar(string title, string content, int index, int max)
  45. {
  46. EditorUtility.DisplayProgressBar($"{title}({index}/{max}) ", content,
  47. index * 1f / max);
  48. }
  49. public void BuildBundles()
  50. {
  51. var assetBundleNames = AssetDatabase.GetAllAssetBundleNames();
  52. for (var i = 0; i < assetBundleNames.Length; i++)
  53. {
  54. var assetBundleName = assetBundleNames[i];
  55. DisplayProgressBar("采集资源", assetBundleName, i, assetBundleNames.Length);
  56. var assetNames = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
  57. bundledAssets.AddRange(Array.ConvertAll(assetNames, input => new Asset
  58. {
  59. path = input,
  60. bundle = assetBundleName
  61. }));
  62. }
  63. CheckAssets();
  64. EditorUtility.ClearProgressBar();
  65. FinishBuild();
  66. }
  67. public void BuildCustomBundles(string[] resRootDirNames, string setName)
  68. {
  69. List<string> hideFilePathList = new List<string>();
  70. List<string> hideDirPahtList = new List<string>();
  71. //换装资源打包屏蔽
  72. SqliteController.Instance.dirPath = Path.Combine(Environment.CurrentDirectory, ResPathUtil.CONFIG_DIR_PATH);
  73. SqliteController.Instance.Init(false, null);
  74. var dressUpItemList = ItemCfgArray.Instance.GetCfgsByitemType(ConstItemType.DRESS_UP);
  75. foreach (var itemCfg in dressUpItemList)
  76. {
  77. if (itemCfg.isHide <= 0)
  78. {
  79. continue;
  80. }
  81. if (!string.IsNullOrEmpty(itemCfg.resLayer1))
  82. {
  83. HideItemRes(itemCfg, 1, hideFilePathList, hideDirPahtList);
  84. }
  85. if (!string.IsNullOrEmpty(itemCfg.resLayer2))
  86. {
  87. HideItemRes(itemCfg, 2, hideFilePathList, hideDirPahtList);
  88. }
  89. if (!string.IsNullOrEmpty(itemCfg.resLayer3))
  90. {
  91. HideItemRes(itemCfg, 3, hideFilePathList, hideDirPahtList);
  92. }
  93. }
  94. //套装动作资源打包屏蔽
  95. var suitCfgs = SuitCfgArray.Instance.dataArray;
  96. foreach(var suitCfg in suitCfgs)
  97. {
  98. HideSuitActionRes(suitCfg, hideFilePathList, hideDirPahtList);
  99. }
  100. //卡牌资源打包屏蔽
  101. //var cardCfgs = ItemCfgArray.Instance.GetCfgsByitemType(ConstItemType.CARD);
  102. //foreach(var itemCfg in cardCfgs)
  103. //{
  104. // HideCardRes(itemCfg, hideFilePathList, hideDirPahtList);
  105. //}
  106. foreach (var resRootDirName in resRootDirNames)
  107. {
  108. CreateBundles(resRootDirName, setName, hideFilePathList, hideDirPahtList);
  109. }
  110. CheckAssets();
  111. EditorUtility.ClearProgressBar();
  112. FinishBuild();
  113. }
  114. private void HideItemRes(ItemCfg itemCfg, int layerId, List<string> hideFilePathList, List<string> hideDirPahtList)
  115. {
  116. string res = DressUpUtil.GetDressUpItemLayerRes(itemCfg, layerId);
  117. //部件图
  118. var resPath = ResPathUtil.GetDressUpPath(res, ItemUtil.GetItemResExt(itemCfg.itemType, itemCfg.subType));
  119. hideFilePathList.Add(resPath);
  120. //动画
  121. resPath = ResPathUtil.GetDressUpAnimationDirPath(res);
  122. hideDirPahtList.Add(resPath);
  123. //特效
  124. resPath = ResPathUtil.GetDressUpEffectDirPath(res);
  125. hideDirPahtList.Add(resPath);
  126. resPath = ResPathUtil.GetDressUpEffectDirPath(res, true);
  127. hideDirPahtList.Add(resPath);
  128. }
  129. private void HideSuitActionRes(SuitCfg suitCfg, List<string> hideFilePathList, List<string> hideDirPahtList)
  130. {
  131. if(suitCfg.isHide <= 0)
  132. {
  133. return;
  134. }
  135. string resPath;
  136. //动画
  137. if(!string.IsNullOrEmpty(suitCfg.aniRes))
  138. {
  139. resPath = ResPathUtil.GetDressUpAnimationDirPath(suitCfg.aniRes);
  140. hideDirPahtList.Add(resPath);
  141. }
  142. //特效
  143. if (!string.IsNullOrEmpty(suitCfg.effRes))
  144. {
  145. resPath = ResPathUtil.GetDressUpEffectDirPath(suitCfg.effRes);
  146. hideDirPahtList.Add(resPath);
  147. resPath = ResPathUtil.GetDressUpEffectDirPath(suitCfg.effRes, true);
  148. hideDirPahtList.Add(resPath);
  149. }
  150. }
  151. //private void HideCardRes(ItemCfg itemCfg, List<string> hideFilePathList, List<string> hideDirPahtList)
  152. //{
  153. // //大图
  154. // var resPath = ResPathUtil.GetCardPath(itemCfg.res);
  155. // hideFilePathList.Add(resPath);
  156. // //小图
  157. // resPath = ResPathUtil.GetCardSmallPath(itemCfg.res);
  158. // hideFilePathList.Add(resPath);
  159. // //动画
  160. // resPath = ResPathUtil.GetCardAnimationDirPath(itemCfg.res);
  161. // hideDirPahtList.Add(resPath);
  162. // //特效
  163. // //to do...暂时没有
  164. //}
  165. private void CreateBundles(string resRootDirName, string setName, List<string> hideFilePathList, List<string> hideDirPahtList)
  166. {
  167. var path = Path.Combine(Application.dataPath, resRootDirName);
  168. var buildSetting = GFGEditor.BuildSetting.GetBuildSetting(setName);
  169. var dirBundleList = buildSetting.dirBundleList;
  170. var excludeDirs = buildSetting.dirBundleList.GetRange(0, buildSetting.dirBundleList.Count);
  171. excludeDirs.AddRange(EXCLUDE_DIRS);
  172. GFGEditor.FileUtil.ForeachFileInDir(path, excludeDirs, (string file) =>
  173. {
  174. var ext = Path.GetExtension(file);
  175. if (Array.IndexOf(EXCLUDE_EXTS, ext) < 0)
  176. {
  177. file = file.Replace('\\', '/');
  178. string curDir = Environment.CurrentDirectory.Replace("\\", "/");
  179. string filePath = file.Replace(curDir + "/", "");
  180. if(hideFilePathList.Contains(filePath))
  181. {
  182. return;
  183. }
  184. EditorUtility.DisplayProgressBar("采集资源", filePath, 1f);
  185. var bundle = filePath.Replace($"Assets/{resRootDirName}/", "");
  186. bundle = bundle.Replace('/', '_');
  187. var i = bundle.IndexOf(".");
  188. bundle = bundle.Substring(0, i);
  189. bundle = bundle.ToLower();
  190. //以文件名标识分组
  191. for (int j = 0; j < buildSetting.dirTypeList.Count; j++)
  192. {
  193. string str = buildSetting.dirTypeList[j];
  194. if (bundle.IndexOf(str) >= 0)
  195. {
  196. bundle = str.Substring(0, str.Length - 1);
  197. break;
  198. }
  199. }
  200. bundledAssets.Add(new Asset
  201. {
  202. path = filePath,
  203. bundle = bundle
  204. });
  205. }
  206. });
  207. //以子文件夹为单位分组
  208. foreach (var dir in dirBundleList)
  209. {
  210. var dirPath = Path.Combine(Environment.CurrentDirectory, dir);
  211. if (!GFGEditor.FileUtil.CheckPathInParent(dirPath, path))
  212. {
  213. continue;
  214. }
  215. GFGEditor.FileUtil.ForeachDirInDir(dirPath, (string subDirPath) =>
  216. {
  217. var targetDirPath = subDirPath.Replace('\\', '/');
  218. string curDirPath = Environment.CurrentDirectory.Replace("\\", "/");
  219. string subDir = targetDirPath.Replace(curDirPath + "/", "");
  220. if(hideDirPahtList.Contains(subDir))
  221. {
  222. return;
  223. }
  224. var bundle = subDir.Replace($"Assets/{resRootDirName}/", "");
  225. bundle = bundle.Replace('/', '_');
  226. bundle = bundle.ToLower();
  227. GFGEditor.FileUtil.ForeachFileInDir(subDirPath, null, (string file) =>
  228. {
  229. file = file.Replace('\\', '/');
  230. string curDir = Environment.CurrentDirectory.Replace("\\", "/");
  231. string filePath = file.Replace(curDir + "/", "");
  232. EditorUtility.DisplayProgressBar("采集资源", filePath, 1f);
  233. bundledAssets.Add(new Asset
  234. {
  235. path = filePath,
  236. bundle = bundle
  237. });
  238. });
  239. });
  240. }
  241. }
  242. private void CheckAssets()
  243. {
  244. for (var i = 0; i < bundledAssets.Count; i++)
  245. {
  246. var asset = bundledAssets[i];
  247. //去重
  248. if (!pathWithAssets.TryGetValue(asset.path, out var ba))
  249. {
  250. pathWithAssets[asset.path] = asset;
  251. }
  252. else
  253. {
  254. bundledAssets.RemoveAt(i);
  255. i--;
  256. Debug.LogWarningFormat("{0} can't pack with {1}, because already pack to {2}", asset.path,
  257. asset.bundle, ba.bundle);
  258. }
  259. }
  260. }
  261. private void FinishBuild()
  262. {
  263. var bundles = new List<ManifestBundle>();
  264. var dictionary = new Dictionary<string, List<string>>();
  265. //分组
  266. foreach (var asset in bundledAssets)
  267. {
  268. if (!dictionary.TryGetValue(asset.bundle, out var assets))
  269. {
  270. assets = new List<string>();
  271. dictionary.Add(asset.bundle, assets);
  272. bundles.Add(new ManifestBundle
  273. {
  274. name = asset.bundle,
  275. assets = assets
  276. });
  277. }
  278. assets.Add(asset.path);
  279. }
  280. var unityBuildPath = Settings.PlatformBuildPath;
  281. if (!string.IsNullOrEmpty(GFGGame.LauncherConfig.resKey))
  282. {
  283. unityBuildPath = Settings.UnityBuildPath;
  284. }
  285. if (bundles.Count <= 0) return;
  286. var manifest = BuildPipeline.BuildAssetBundles(unityBuildPath, bundles.ConvertAll(bundle =>
  287. new AssetBundleBuild
  288. {
  289. assetNames = bundle.assets.ToArray(),
  290. assetBundleName = bundle.name
  291. }).ToArray(),
  292. buildAssetBundleOptions | BuildAssetBundleOptions.AppendHashToAssetBundleName,
  293. EditorUserBuildSettings.activeBuildTarget);
  294. if (manifest == null)
  295. {
  296. Debug.LogErrorFormat("Failed to build {0}.", name);
  297. return;
  298. }
  299. //if (!string.IsNullOrEmpty(GFGGame.LauncherConfig.resKey))
  300. //{
  301. // string buildPath = Settings.PlatformBuildPath;
  302. // CreateEncryptAssets(unityBuildPath, buildPath, manifest, GFGGame.LauncherConfig.resKey);
  303. //}
  304. AfterBuildBundles(bundles, manifest);
  305. }
  306. /// <summary>
  307. /// 创建加密的AssetBundle
  308. /// </summary>
  309. //public static void CreateEncryptAssets(string bundlePackagePath, string encryptAssetPath, AssetBundleManifest manifest, string secretKey)
  310. //{
  311. // if (!Directory.Exists(encryptAssetPath))
  312. // {
  313. // Directory.CreateDirectory(encryptAssetPath);
  314. // }
  315. // string[] assetBundles = manifest.GetAllAssetBundles();
  316. // foreach (string assetBundle in assetBundles)
  317. // {
  318. // string bundlePath = Path.Combine(bundlePackagePath, assetBundle);
  319. // byte[] encryptBytes = EncryptHelper.CreateEncryptData(bundlePath, secretKey);
  320. // using (FileStream fs = new FileStream(Path.Combine(encryptAssetPath, assetBundle), FileMode.OpenOrCreate))
  321. // {
  322. // fs.SetLength(0);
  323. // fs.Write(encryptBytes, 0, encryptBytes.Length);
  324. // }
  325. // }
  326. //}
  327. /// <summary>
  328. /// 创建加密的AssetBundle
  329. /// </summary>
  330. public static void CreateEncryptAsset(string unityBundlesPath, string bundlesPath, string unityBundle, string secretKey)
  331. {
  332. if (!Directory.Exists(bundlesPath))
  333. {
  334. Directory.CreateDirectory(bundlesPath);
  335. }
  336. string unityBundlePath = Path.Combine(unityBundlesPath, unityBundle);
  337. byte[] encryptBytes = EncryptHelper.CreateEncryptData(unityBundlePath, secretKey);
  338. using (FileStream fs = new FileStream(Path.Combine(bundlesPath, unityBundle), FileMode.OpenOrCreate))
  339. {
  340. fs.SetLength(0);
  341. fs.Write(encryptBytes, 0, encryptBytes.Length);
  342. }
  343. }
  344. private string GetOriginBundle(string assetBundle)
  345. {
  346. var pos = assetBundle.LastIndexOf("_", StringComparison.Ordinal) + 1;
  347. var hash = assetBundle.Substring(pos);
  348. if (!string.IsNullOrEmpty(bundleExtension)) hash = hash.Replace(bundleExtension, "");
  349. var originBundle = $"{assetBundle.Replace("_" + hash, "")}";
  350. return originBundle;
  351. }
  352. private void AfterBuildBundles(List<ManifestBundle> bundles,
  353. AssetBundleManifest manifest)
  354. {
  355. var nameWithBundles = new Dictionary<string, ManifestBundle>();
  356. for (var i = 0; i < bundles.Count; i++)
  357. {
  358. var bundle = bundles[i];
  359. bundle.id = i;
  360. nameWithBundles[bundle.name] = bundle;
  361. }
  362. if (manifest != null)
  363. {
  364. var assetBundles = manifest.GetAllAssetBundles();
  365. foreach (var assetBundle in assetBundles)
  366. {
  367. var originBundle = GetOriginBundle(assetBundle);
  368. var dependencies = Array.ConvertAll(manifest.GetAllDependencies(assetBundle), GetOriginBundle);
  369. if (nameWithBundles.TryGetValue(originBundle, out var manifestBundle))
  370. {
  371. manifestBundle.nameWithAppendHash = assetBundle;
  372. manifestBundle.dependencies = Array.ConvertAll(dependencies, input => nameWithBundles[input].id);
  373. }
  374. else
  375. {
  376. Debug.LogErrorFormat("Bundle not exist: {0}", originBundle);
  377. }
  378. }
  379. }
  380. CreateManifest(bundles);
  381. }
  382. private void CreateManifest(List<ManifestBundle> bundles)
  383. {
  384. var manifest = Settings.GetManifest();
  385. manifest.version++;
  386. manifest.appVersion = UnityEditor.PlayerSettings.bundleVersion;
  387. var getBundles = manifest.GetBundles();
  388. var newFiles = new List<string>();
  389. var newSize = 0L;
  390. foreach (var bundle in bundles)
  391. {
  392. if (!getBundles.TryGetValue(bundle.name, out var value) ||
  393. value.nameWithAppendHash != bundle.nameWithAppendHash)
  394. {
  395. newFiles.Add(bundle.nameWithAppendHash);
  396. if (!string.IsNullOrEmpty(GFGGame.LauncherConfig.resKey))
  397. {
  398. string buildPath = Settings.PlatformBuildPath;
  399. CreateEncryptAsset(Settings.UnityBuildPath, buildPath, bundle.nameWithAppendHash, GFGGame.LauncherConfig.resKey);
  400. }
  401. }
  402. var file = Settings.GetBuildPath(bundle.nameWithAppendHash);
  403. if (File.Exists(file))
  404. using (var stream = File.OpenRead(file))
  405. {
  406. bundle.size = stream.Length;
  407. bundle.crc = Utility.ComputeCRC32(stream);
  408. }
  409. else
  410. Debug.LogErrorFormat("File not found: {0}", file);
  411. newSize += bundle.size;
  412. }
  413. manifest.bundles = bundles;
  414. var newFilesSize = Utility.FormatBytes(newSize);
  415. newFiles.AddRange(WriteManifest(manifest));
  416. // write upload files
  417. var filename = Settings.GetBuildPath($"upload_files_for_{manifest.name}_{manifest.version}.txt");
  418. File.WriteAllText(filename, string.Join("\n", newFiles.ToArray()));
  419. record = new Record
  420. {
  421. build = name,
  422. version = manifest.version,
  423. files = newFiles,
  424. size = newSize,
  425. time = DateTime.Now.ToFileTime()
  426. };
  427. WriteRecord(record);
  428. Debug.LogFormat("Build bundles with {0}({1}) files with version {2} for {3}.", newFiles.Count, newFilesSize,
  429. manifest.version, manifest.name);
  430. }
  431. private static IEnumerable<string> WriteManifest(Manifest manifest)
  432. {
  433. var newFiles = new List<string>();
  434. var filename = $"{manifest.name}";
  435. var version = manifest.version;
  436. WriteJson(manifest, filename, newFiles);
  437. var path = Settings.GetBuildPath(filename);
  438. var crc = Utility.ComputeCRC32(path);
  439. var info = new FileInfo(path);
  440. WriteJson(manifest, $"{filename}_v{version}_{crc}", newFiles);
  441. // for version file
  442. var manifestVersion = ScriptableObject.CreateInstance<ManifestVersion>();
  443. manifestVersion.crc = crc;
  444. manifestVersion.size = info.Length;
  445. manifestVersion.version = version;
  446. manifestVersion.appVersion = manifest.appVersion;
  447. WriteJson(manifestVersion, Manifest.GetVersionFile(filename), newFiles);
  448. WriteJson(manifestVersion, $"{filename}_v{version}_{crc}.version", newFiles);
  449. return newFiles;
  450. }
  451. private static void WriteJson(ScriptableObject so, string file, List<string> newFiles)
  452. {
  453. newFiles.Add(file);
  454. var json = JsonUtility.ToJson(so);
  455. File.WriteAllText(Settings.GetBuildPath(file), json);
  456. }
  457. }
  458. }