BuildTask.cs 21 KB

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