BuildTask.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using UnityEditor;
  5. using UnityEngine;
  6. namespace VEngine.Editor.Builds
  7. {
  8. public class BuildTask
  9. {
  10. private readonly string[] EXCLUDE_EXTS = new string[] { ".meta" };
  11. private readonly string[] EXCLUDE_DIRS = new string[] { "Assets/Res/.svn" };
  12. private readonly BuildAssetBundleOptions buildAssetBundleOptions;
  13. private readonly List<Asset> bundledAssets = new List<Asset>();
  14. private readonly string bundleExtension;
  15. public readonly string name;
  16. private readonly Dictionary<string, Asset> pathWithAssets = new Dictionary<string, Asset>();
  17. public BuildTask()
  18. {
  19. name = nameof(Manifest);
  20. buildAssetBundleOptions = BuildAssetBundleOptions.ChunkBasedCompression |
  21. BuildAssetBundleOptions.AppendHashToAssetBundleName;
  22. bundleExtension = ".unity3d";
  23. }
  24. public Record record { get; private set; }
  25. private static string GetRecordsPath(string buildName)
  26. {
  27. return Settings.GetBuildPath($"build_records_for_{buildName}.json");
  28. }
  29. private static void WriteRecord(Record record)
  30. {
  31. var records = GetRecords(record.build);
  32. records.data.Insert(0, record);
  33. File.WriteAllText(GetRecordsPath(record.build), JsonUtility.ToJson(records));
  34. }
  35. private static Records GetRecords(string build)
  36. {
  37. var records = ScriptableObject.CreateInstance<Records>();
  38. var path = GetRecordsPath(build);
  39. if (File.Exists(path)) JsonUtility.FromJsonOverwrite(File.ReadAllText(path), records);
  40. return records;
  41. }
  42. private static void DisplayProgressBar(string title, string content, int index, int max)
  43. {
  44. EditorUtility.DisplayProgressBar($"{title}({index}/{max}) ", content,
  45. index * 1f / max);
  46. }
  47. public void BuildBundles()
  48. {
  49. var assetBundleNames = AssetDatabase.GetAllAssetBundleNames();
  50. for (var i = 0; i < assetBundleNames.Length; i++)
  51. {
  52. var assetBundleName = assetBundleNames[i];
  53. DisplayProgressBar("采集资源", assetBundleName, i, assetBundleNames.Length);
  54. var assetNames = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
  55. bundledAssets.AddRange(Array.ConvertAll(assetNames, input => new Asset
  56. {
  57. path = input,
  58. bundle = assetBundleName
  59. }));
  60. }
  61. CheckAssets();
  62. EditorUtility.ClearProgressBar();
  63. FinishBuild();
  64. }
  65. public void BuildCustomBundles(string[] resRootDirNames)
  66. {
  67. foreach(var resRootDirName in resRootDirNames)
  68. {
  69. CreateBundles(resRootDirName);
  70. }
  71. CheckAssets();
  72. EditorUtility.ClearProgressBar();
  73. FinishBuild();
  74. }
  75. private void CreateBundles(string resRootDirName)
  76. {
  77. var path = Path.Combine(Application.dataPath, resRootDirName);
  78. var buildSetting = GFGEditor.BuildSetting.GetBuildSetting();
  79. var dirBundleList = buildSetting.dirBundleList;
  80. var excludeDirs = dirBundleList.GetRange(0, dirBundleList.Count);
  81. excludeDirs.AddRange(EXCLUDE_DIRS);
  82. //检测单个文件打包
  83. GFGEditor.FileUtil.ForeachFileInDir(path, excludeDirs, (string file) =>
  84. {
  85. var ext = Path.GetExtension(file);
  86. if (Array.IndexOf(EXCLUDE_EXTS, ext) < 0)
  87. {
  88. file = file.Replace('\\', '/');
  89. string curDir = Environment.CurrentDirectory.Replace("\\", "/");
  90. string filePath = file.Replace(curDir + "/", "");
  91. EditorUtility.DisplayProgressBar("采集资源", filePath, 1f);
  92. var bundle = filePath.Replace($"Assets/{resRootDirName}/", "");
  93. bundle = bundle.Replace('/', '_');
  94. var i = bundle.IndexOf(".");
  95. bundle = bundle.Substring(0, i);
  96. bundle = bundle.ToLower();
  97. bundledAssets.Add(new Asset
  98. {
  99. path = filePath,
  100. bundle = bundle
  101. });
  102. }
  103. });
  104. //检测按文件夹打包
  105. foreach (var dir in dirBundleList)
  106. {
  107. var dirPath = Path.Combine(Environment.CurrentDirectory, dir);
  108. if(!GFGEditor.FileUtil.CheckPathInParent(dirPath, path))
  109. {
  110. continue;
  111. }
  112. GFGEditor.FileUtil.ForeachDirInDir(dirPath, (string subDirPath) =>
  113. {
  114. var targetDirPath = subDirPath.Replace('\\', '/');
  115. string curDirPath = Environment.CurrentDirectory.Replace("\\", "/");
  116. string subDir = targetDirPath.Replace(curDirPath + "/", "");
  117. var bundle = subDir.Replace($"Assets/{resRootDirName}/", "");
  118. bundle = bundle.Replace('/', '_');
  119. bundle = bundle.ToLower();
  120. GFGEditor.FileUtil.ForeachFileInDir(subDirPath, null, (string file) =>
  121. {
  122. var ext = Path.GetExtension(file);
  123. file = file.Replace('\\', '/');
  124. string curDir = Environment.CurrentDirectory.Replace("\\", "/");
  125. string filePath = file.Replace(curDir + "/", "");
  126. EditorUtility.DisplayProgressBar("采集资源", filePath, 1f);
  127. bundledAssets.Add(new Asset
  128. {
  129. path = filePath,
  130. bundle = bundle
  131. });
  132. });
  133. });
  134. }
  135. }
  136. private void CheckAssets()
  137. {
  138. for (var i = 0; i < bundledAssets.Count; i++)
  139. {
  140. var asset = bundledAssets[i];
  141. if (!pathWithAssets.TryGetValue(asset.path, out var ba))
  142. {
  143. pathWithAssets[asset.path] = asset;
  144. }
  145. else
  146. {
  147. bundledAssets.RemoveAt(i);
  148. i--;
  149. Debug.LogWarningFormat("{0} can't pack with {1}, because already pack to {2}", asset.path,
  150. asset.bundle, ba.bundle);
  151. }
  152. }
  153. }
  154. private void FinishBuild()
  155. {
  156. var bundles = new List<ManifestBundle>();
  157. var dictionary = new Dictionary<string, List<string>>();
  158. foreach (var asset in bundledAssets)
  159. {
  160. if (!dictionary.TryGetValue(asset.bundle, out var assets))
  161. {
  162. assets = new List<string>();
  163. dictionary.Add(asset.bundle, assets);
  164. bundles.Add(new ManifestBundle
  165. {
  166. name = asset.bundle,
  167. assets = assets
  168. });
  169. }
  170. assets.Add(asset.path);
  171. }
  172. var outputPath = Settings.PlatformBuildPath;
  173. if (bundles.Count <= 0) return;
  174. var manifest = BuildPipeline.BuildAssetBundles(outputPath, bundles.ConvertAll(bundle =>
  175. new AssetBundleBuild
  176. {
  177. assetNames = bundle.assets.ToArray(),
  178. assetBundleName = bundle.name
  179. }).ToArray(),
  180. buildAssetBundleOptions | BuildAssetBundleOptions.AppendHashToAssetBundleName,
  181. EditorUserBuildSettings.activeBuildTarget);
  182. if (manifest == null)
  183. {
  184. Debug.LogErrorFormat("Failed to build {0}.", name);
  185. return;
  186. }
  187. AfterBuildBundles(bundles, manifest);
  188. }
  189. private string GetOriginBundle(string assetBundle)
  190. {
  191. var pos = assetBundle.LastIndexOf("_", StringComparison.Ordinal) + 1;
  192. var hash = assetBundle.Substring(pos);
  193. if (!string.IsNullOrEmpty(bundleExtension)) hash = hash.Replace(bundleExtension, "");
  194. var originBundle = $"{assetBundle.Replace("_" + hash, "")}";
  195. return originBundle;
  196. }
  197. private void AfterBuildBundles(List<ManifestBundle> bundles,
  198. AssetBundleManifest manifest)
  199. {
  200. var nameWithBundles = new Dictionary<string, ManifestBundle>();
  201. for (var i = 0; i < bundles.Count; i++)
  202. {
  203. var bundle = bundles[i];
  204. bundle.id = i;
  205. nameWithBundles[bundle.name] = bundle;
  206. }
  207. if (manifest != null)
  208. {
  209. var assetBundles = manifest.GetAllAssetBundles();
  210. foreach (var assetBundle in assetBundles)
  211. {
  212. var originBundle = GetOriginBundle(assetBundle);
  213. var dependencies =
  214. Array.ConvertAll(manifest.GetAllDependencies(assetBundle), GetOriginBundle);
  215. if (nameWithBundles.TryGetValue(originBundle, out var manifestBundle))
  216. {
  217. manifestBundle.nameWithAppendHash = assetBundle;
  218. manifestBundle.dependencies =
  219. Array.ConvertAll(dependencies, input => nameWithBundles[input].id);
  220. var file = Settings.GetBuildPath(assetBundle);
  221. if (File.Exists(file))
  222. using (var stream = File.OpenRead(file))
  223. {
  224. manifestBundle.size = stream.Length;
  225. manifestBundle.crc = Utility.ComputeCRC32(stream);
  226. }
  227. else
  228. Debug.LogErrorFormat("File not found: {0}", file);
  229. }
  230. else
  231. {
  232. Debug.LogErrorFormat("Bundle not exist: {0}", originBundle);
  233. }
  234. }
  235. }
  236. CreateManifest(bundles);
  237. }
  238. private void CreateManifest(List<ManifestBundle> bundles)
  239. {
  240. var manifest = Settings.GetManifest();
  241. manifest.version++;
  242. manifest.appVersion = UnityEditor.PlayerSettings.bundleVersion;
  243. var getBundles = manifest.GetBundles();
  244. var newFiles = new List<string>();
  245. var newSize = 0L;
  246. foreach (var bundle in bundles)
  247. if (!getBundles.TryGetValue(bundle.name, out var value) ||
  248. value.nameWithAppendHash != bundle.nameWithAppendHash)
  249. {
  250. newFiles.Add(bundle.nameWithAppendHash);
  251. newSize += bundle.size;
  252. }
  253. manifest.bundles = bundles;
  254. var newFilesSize = Utility.FormatBytes(newSize);
  255. newFiles.AddRange(WriteManifest(manifest));
  256. // write upload files
  257. var filename = Settings.GetBuildPath($"upload_files_for_{manifest.name}_{manifest.version}.txt");
  258. File.WriteAllText(filename, string.Join("\n", newFiles.ToArray()));
  259. record = new Record
  260. {
  261. build = name,
  262. version = manifest.version,
  263. files = newFiles,
  264. size = newSize,
  265. time = DateTime.Now.ToFileTime()
  266. };
  267. WriteRecord(record);
  268. Debug.LogFormat("Build bundles with {0}({1}) files with version {2} for {3}.", newFiles.Count, newFilesSize,
  269. manifest.version, manifest.name);
  270. }
  271. private static IEnumerable<string> WriteManifest(Manifest manifest)
  272. {
  273. var newFiles = new List<string>();
  274. var filename = $"{manifest.name}";
  275. var version = manifest.version;
  276. WriteJson(manifest, filename, newFiles);
  277. var path = Settings.GetBuildPath(filename);
  278. var crc = Utility.ComputeCRC32(path);
  279. var info = new FileInfo(path);
  280. WriteJson(manifest, $"{filename}_v{version}_{crc}", newFiles);
  281. // for version file
  282. var manifestVersion = ScriptableObject.CreateInstance<ManifestVersion>();
  283. manifestVersion.crc = crc;
  284. manifestVersion.size = info.Length;
  285. manifestVersion.version = version;
  286. manifestVersion.appVersion = manifest.appVersion;
  287. WriteJson(manifestVersion, Manifest.GetVersionFile(filename), newFiles);
  288. WriteJson(manifestVersion, $"{filename}_v{version}_{crc}.version", newFiles);
  289. return newFiles;
  290. }
  291. private static void WriteJson(ScriptableObject so, string file, List<string> newFiles)
  292. {
  293. newFiles.Add(file);
  294. var json = JsonUtility.ToJson(so);
  295. File.WriteAllText(Settings.GetBuildPath(file), json);
  296. }
  297. }
  298. }