BuildTask.cs 21 KB

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