BuildTask.cs 21 KB

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