BuildTask.cs 21 KB

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