HotPatchBundleBuild.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using TMPro;
  6. using UnityEditor;
  7. using UnityEditor.Build;
  8. using UnityEngine;
  9. namespace HotPatch.Editor
  10. {
  11. public static class HotPatchBundleBuild
  12. {
  13. public static string AotDirectory => Path.Combine(Application.dataPath, "AotDlls");
  14. const string AotAssetDirectory = "Assets/AotDlls";
  15. const string DllAssetDirectory = "Assets/HotPatch/BundleInputs";
  16. public static string FindScenePath(string sceneName)
  17. {
  18. var paths = AssetDatabase.FindAssets("t:Scene", new[] { "Assets" }).Select(AssetDatabase.GUIDToAssetPath)
  19. .Where(p => Path.GetFileNameWithoutExtension(p) == sceneName).ToArray();
  20. if (paths.Length != 1) throw new InvalidOperationException("场景必须存在且名称唯一: " + sceneName);
  21. return paths[0];
  22. }
  23. public static void ConfigurePlayerScenes()
  24. {
  25. var launchPath = FindScenePath("Launch");
  26. if (EditorUserBuildSettings.buildScriptsOnly)
  27. {
  28. EditorUserBuildSettings.buildScriptsOnly = false;
  29. Debug.Log("[资源构建] 已关闭 Force skip data build,下一次安装包构建将正常更新场景和资源数据。");
  30. }
  31. if (!ContainsOnlyLaunch(EditorBuildSettings.scenes, launchPath))
  32. {
  33. EditorBuildSettings.scenes = new[] { new EditorBuildSettingsScene(launchPath, true) };
  34. Debug.Log("[资源构建] 已调整构建场景列表,仅保留并启用 Launch: " + launchPath);
  35. }
  36. var profile = UnityEditor.Build.Profile.BuildProfile.GetActiveBuildProfile();
  37. if (profile != null && profile.overrideGlobalScenes && !ContainsOnlyLaunch(profile.scenes, launchPath))
  38. {
  39. profile.scenes = new[] { new EditorBuildSettingsScene(launchPath, true) };
  40. EditorUtility.SetDirty(profile);
  41. AssetDatabase.SaveAssetIfDirty(profile);
  42. Debug.Log("[资源构建] 已调整当前构建配置的场景列表,仅保留并启用 Launch: " + launchPath);
  43. }
  44. }
  45. static bool ContainsOnlyLaunch(EditorBuildSettingsScene[] scenes, string launchPath)
  46. => scenes != null && scenes.Length == 1 && scenes[0].path == launchPath && scenes[0].enabled;
  47. public static void PrepareAotFiles(IReadOnlyDictionary<string, string> files)
  48. {
  49. if (!files.Keys.OrderBy(n => n).SequenceEqual(HotPatchBundleLoader.AotAssemblyNames.OrderBy(n => n)))
  50. throw new InvalidDataException("Assets/AotDlls 必须包含 mscorlib、Newtonsoft.Json、System.Core 和 UniTask 四个程序集。");
  51. foreach (var file in files)
  52. {
  53. if (!File.Exists(file.Value)) throw new FileNotFoundException("当前平台 AOT 基线缺失。", file.Value);
  54. if (System.Reflection.AssemblyName.GetAssemblyName(file.Value).Name + ".dll" != file.Key)
  55. throw new InvalidDataException("AOT 文件与程序集名称不一致: " + file.Key);
  56. }
  57. Directory.CreateDirectory(AotDirectory);
  58. foreach (var file in files) File.Copy(file.Value, Path.Combine(AotDirectory, file.Key + ".bytes"), true);
  59. AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
  60. }
  61. static void PrepareDynamicFonts()
  62. {
  63. var fonts = AssetDatabase.FindAssets("t:TMP_FontAsset")
  64. .Select(AssetDatabase.GUIDToAssetPath)
  65. .Select(AssetDatabase.LoadAssetAtPath<TMP_FontAsset>)
  66. .Where(font => font != null && new SerializedObject(font).FindProperty("m_ClearDynamicDataOnBuild").boolValue &&
  67. (font.atlasPopulationMode == AtlasPopulationMode.Dynamic ||
  68. font.atlasPopulationMode == AtlasPopulationMode.DynamicOS)).ToArray();
  69. if (fonts.Length == 0) return;
  70. new TMP_PreBuildProcessor().OnPreprocessBuild(null);
  71. foreach (var font in fonts)
  72. {
  73. EditorUtility.SetDirty(font);
  74. foreach (var texture in font.atlasTextures)
  75. if (texture != null) EditorUtility.SetDirty(texture);
  76. AssetDatabase.SaveAssetIfDirty(font);
  77. }
  78. Debug.Log("[资源构建] 已按 Clear Dynamic Data On Build 设置清理动态字体缓存: " +
  79. string.Join(", ", fonts.Select(AssetDatabase.GetAssetPath)));
  80. }
  81. public static HotPatchManifest Build(string destination, string dll, IReadOnlyDictionary<string, string> aotFiles,
  82. string assemblyName, string sceneName, string platform, string buildId, bool development, bool includeAot,
  83. HotPatchManifest original = null)
  84. {
  85. if (!includeAot && original?.aotBundle == null)
  86. throw new InvalidDataException("构建更新 Bundle 前必须提供原始 AOT 清单。");
  87. var target = (BuildTarget)Enum.Parse(typeof(BuildTarget), platform);
  88. if (target != EditorUserBuildSettings.activeBuildTarget)
  89. throw new InvalidOperationException("请先切换到目标平台再构建 Bundle。");
  90. var scenePath = FindScenePath(sceneName);
  91. if (includeAot) PrepareAotFiles(aotFiles);
  92. Directory.CreateDirectory(DllAssetDirectory);
  93. var dllAsset = DllAssetDirectory + "/" + assemblyName + ".dll.bytes";
  94. File.Copy(dll, dllAsset, true);
  95. AssetDatabase.ImportAsset(dllAsset, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate);
  96. var assemblyBundleName = HotPatchResource.AssemblyBundleName(assemblyName);
  97. var sceneBundleName = HotPatchResource.SceneBundleName(sceneName);
  98. var builds = new List<AssetBundleBuild>
  99. {
  100. new AssetBundleBuild { assetBundleName = assemblyBundleName, assetNames = new[] { dllAsset },
  101. addressableNames = new[] { assemblyName + ".dll.bytes" } },
  102. new AssetBundleBuild { assetBundleName = sceneBundleName, assetNames = new[] { scenePath } }
  103. };
  104. if (includeAot)
  105. {
  106. var paths = Directory.GetFiles(AotDirectory, "*.bytes", SearchOption.AllDirectories)
  107. .Select(p => AotAssetDirectory + "/" + p.Substring(AotDirectory.Length + 1).Replace('\\', '/')).OrderBy(p => p).ToArray();
  108. var expected = HotPatchBundleLoader.AotAssemblyNames.Select(n => n + ".bytes").OrderBy(n => n).ToArray();
  109. if (!paths.Select(Path.GetFileName).OrderBy(n => n).SequenceEqual(expected))
  110. throw new InvalidDataException("Assets/AotDlls 目录只能包含指定的四个 .dll.bytes 文件。");
  111. builds.Insert(0, new AssetBundleBuild { assetBundleName = "aot.bundle", assetNames = paths,
  112. addressableNames = paths.Select(Path.GetFileName).ToArray() });
  113. }
  114. var output = Path.GetFullPath("Build/HotUpdate/BundleCache/" + platform);
  115. Directory.CreateDirectory(output);
  116. var options = BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.StrictMode;
  117. PrepareDynamicFonts();
  118. AssetBundleManifest result;
  119. using (new HotPatchAndroidResolverScope())
  120. result = BuildPipeline.BuildAssetBundles(output, builds.ToArray(), options, target);
  121. if (result == null) throw new BuildFailedException("AssetBundle 构建失败,未发布资源。");
  122. foreach (var build in builds)
  123. if (result.GetAllDependencies(build.assetBundleName).Length != 0)
  124. throw new BuildFailedException("Bundle 出现未声明依赖: " + build.assetBundleName);
  125. return HotPatchResourcePackage.Write(destination, Path.Combine(output, assemblyBundleName), Path.Combine(output, sceneBundleName),
  126. includeAot ? Path.Combine(output, "aot.bundle") : null, includeAot ? aotFiles : new Dictionary<string, string>(),
  127. assemblyName, sceneName, scenePath, platform, buildId, development, original);
  128. }
  129. }
  130. }