Compare commits

..

No commits in common. "main" and "1.0.2" have entirely different histories.
main ... 1.0.2

1393 changed files with 10469 additions and 241348 deletions

File diff suppressed because it is too large Load Diff

View File

@ -8,96 +8,119 @@ namespace YooAsset.Editor
{ {
public class AssetBundleBuilder public class AssetBundleBuilder
{ {
public class BuildParametersContext : IContextObject
{
private readonly System.Diagnostics.Stopwatch _buildWatch = new System.Diagnostics.Stopwatch();
/// <summary>
/// 构建参数
/// </summary>
public BuildParameters Parameters { private set; get; }
/// <summary>
/// 构建管线的输出目录
/// </summary>
public string PipelineOutputDirectory { private set; get; }
public BuildParametersContext(BuildParameters parameters)
{
Parameters = parameters;
PipelineOutputDirectory = AssetBundleBuilderHelper.MakePipelineOutputDirectory(parameters.OutputRoot, parameters.BuildTarget);
}
/// <summary>
/// 获取本次构建的补丁目录
/// </summary>
public string GetPackageDirectory()
{
return $"{Parameters.OutputRoot}/{Parameters.BuildTarget}/{Parameters.BuildVersion}";
}
/// <summary>
/// 获取构建选项
/// </summary>
public BuildAssetBundleOptions GetPipelineBuildOptions()
{
// For the new build system, unity always need BuildAssetBundleOptions.CollectDependencies and BuildAssetBundleOptions.DeterministicAssetBundle
// 除非设置ForceRebuildAssetBundle标记否则会进行增量打包
BuildAssetBundleOptions opt = BuildAssetBundleOptions.None;
opt |= BuildAssetBundleOptions.StrictMode; //Do not allow the build to succeed if any errors are reporting during it.
if (Parameters.CompressOption == ECompressOption.Uncompressed)
opt |= BuildAssetBundleOptions.UncompressedAssetBundle;
else if (Parameters.CompressOption == ECompressOption.LZ4)
opt |= BuildAssetBundleOptions.ChunkBasedCompression;
if (Parameters.ForceRebuild)
opt |= BuildAssetBundleOptions.ForceRebuildAssetBundle; //Force rebuild the asset bundles
if (Parameters.AppendHash)
opt |= BuildAssetBundleOptions.AppendHashToAssetBundleName; //Append the hash to the assetBundle name
if (Parameters.DisableWriteTypeTree)
opt |= BuildAssetBundleOptions.DisableWriteTypeTree; //Do not include type information within the asset bundle (don't write type tree).
if (Parameters.IgnoreTypeTreeChanges)
opt |= BuildAssetBundleOptions.IgnoreTypeTreeChanges; //Ignore the type tree changes when doing the incremental build check.
if (Parameters.DisableLoadAssetByFileName)
{
opt |= BuildAssetBundleOptions.DisableLoadAssetByFileName; //Disables Asset Bundle LoadAsset by file name.
opt |= BuildAssetBundleOptions.DisableLoadAssetByFileNameWithExtension; //Disables Asset Bundle LoadAsset by file name with extension.
}
return opt;
}
/// <summary>
/// 获取构建的耗时(单位:秒)
/// </summary>
public int GetBuildingSeconds()
{
int seconds = (int)(_buildWatch.ElapsedMilliseconds / 1000);
return seconds;
}
public void BeginWatch()
{
_buildWatch.Start();
}
public void StopWatch()
{
_buildWatch.Stop();
}
}
private readonly BuildContext _buildContext = new BuildContext(); private readonly BuildContext _buildContext = new BuildContext();
/// <summary> /// <summary>
/// 开始构建 /// 开始构建
/// </summary> /// </summary>
public BuildResult Run(BuildParameters buildParameters) public bool Run(BuildParameters buildParameters)
{ {
// 清空旧数据 // 清空旧数据
_buildContext.ClearAllContext(); _buildContext.ClearAllContext();
// 检测构建参数是否为空
if (buildParameters == null)
throw new Exception($"{nameof(buildParameters)} is null !");
// 检测可编程构建管线参数
if (buildParameters.BuildPipeline == EBuildPipeline.ScriptableBuildPipeline)
{
if (buildParameters.SBPParameters == null)
throw new Exception($"{nameof(BuildParameters.SBPParameters)} is null !");
if (buildParameters.BuildMode == EBuildMode.DryRunBuild)
throw new Exception($"{nameof(EBuildPipeline.ScriptableBuildPipeline)} not support {nameof(EBuildMode.DryRunBuild)} build mode !");
if (buildParameters.BuildMode == EBuildMode.ForceRebuild)
throw new Exception($"{nameof(EBuildPipeline.ScriptableBuildPipeline)} not support {nameof(EBuildMode.ForceRebuild)} build mode !");
}
// 构建参数 // 构建参数
var buildParametersContext = new BuildParametersContext(buildParameters); var buildParametersContext = new BuildParametersContext(buildParameters);
_buildContext.SetContextObject(buildParametersContext); _buildContext.SetContextObject(buildParametersContext);
// 创建构建节点
List<IBuildTask> pipeline;
if (buildParameters.BuildPipeline == EBuildPipeline.BuiltinBuildPipeline)
{
pipeline = new List<IBuildTask>
{
new TaskPrepare(), //前期准备工作
new TaskGetBuildMap(), //获取构建列表
new TaskBuilding(), //开始执行构建
new TaskCopyRawFile(), //拷贝原生文件
new TaskVerifyBuildResult(), //验证构建结果
new TaskEncryption(), //加密资源文件
new TaskUpdateBundleInfo(), //更新资源包信息
new TaskCreateManifest(), //创建清单文件
new TaskCreateReport(), //创建报告文件
new TaskCreatePackage(), //制作包裹
new TaskCopyBuildinFiles(), //拷贝内置文件
};
}
else if (buildParameters.BuildPipeline == EBuildPipeline.ScriptableBuildPipeline)
{
pipeline = new List<IBuildTask>
{
new TaskPrepare(), //前期准备工作
new TaskGetBuildMap(), //获取构建列表
new TaskBuilding_SBP(), //开始执行构建
new TaskCopyRawFile(), //拷贝原生文件
new TaskVerifyBuildResult_SBP(), //验证构建结果
new TaskEncryption(), //加密资源文件
new TaskUpdateBundleInfo(), //更新补丁信息
new TaskCreateManifest(), //创建清单文件
new TaskCreateReport(), //创建报告文件
new TaskCreatePackage(), //制作补丁包
new TaskCopyBuildinFiles(), //拷贝内置文件
};
}
else
{
throw new NotImplementedException();
}
// 初始化日志
BuildLogger.InitLogger(buildParameters.EnableLog);
// 执行构建流程 // 执行构建流程
var buildResult = BuildRunner.Run(pipeline, _buildContext); List<IBuildTask> pipeline = new List<IBuildTask>
if (buildResult.Success)
{ {
buildResult.OutputPackageDirectory = buildParametersContext.GetPackageOutputDirectory(); new TaskPrepare(), //前期准备工作
BuildLogger.Log($"{buildParameters.BuildMode} pipeline build succeed !"); new TaskGetBuildMap(), //获取构建列表
} new TaskBuilding(), //开始执行构建
else new TaskEncryption(), //加密资源文件
{ new TaskCreatePatchManifest(), //创建清单文件
BuildLogger.Warning($"{buildParameters.BuildMode} pipeline build failed !"); new TaskCreateReport(), //创建报告文件
BuildLogger.Error($"Build task failed : {buildResult.FailedTask}"); new TaskCreatePatchPackage(), //制作补丁包
BuildLogger.Error(buildResult.ErrorInfo); new TaskCopyBuildinFiles(), //拷贝内置文件
} };
return buildResult; bool succeed = BuildRunner.Run(pipeline, _buildContext);
if (succeed)
Debug.Log($"构建成功!");
else
Debug.LogWarning($"构建失败!");
return succeed;
} }
} }
} }

View File

@ -22,7 +22,15 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public static string GetStreamingAssetsFolderPath() public static string GetStreamingAssetsFolderPath()
{ {
return $"{Application.dataPath}/StreamingAssets/{YooAssetSettings.StreamingAssetsBuildinFolder}/"; return $"{Application.dataPath}/StreamingAssets/YooAssets/";
}
/// <summary>
/// 获取构建管线的输出目录
/// </summary>
public static string MakePipelineOutputDirectory(string outputRoot, BuildTarget buildTarget)
{
return $"{outputRoot}/{buildTarget}/{YooAssetSettingsData.Setting.UnityManifestFileName}";
} }
/// <summary> /// <summary>
@ -58,5 +66,69 @@ namespace YooAsset.Editor
} }
} }
} }
/// <summary>
/// 获取所有补丁包版本列表
/// 注意:列表会按照版本号从小到大排序
/// </summary>
private static List<int> GetPackageVersionList(BuildTarget buildTarget, string outputRoot)
{
List<int> versionList = new List<int>();
string parentPath = $"{outputRoot}/{buildTarget}";
if (Directory.Exists(parentPath) == false)
return versionList;
// 获取所有补丁包文件夹
string[] allFolders = Directory.GetDirectories(parentPath);
for (int i = 0; i < allFolders.Length; i++)
{
string folderName = Path.GetFileNameWithoutExtension(allFolders[i]);
if (int.TryParse(folderName, out int version))
versionList.Add(version);
}
// 从小到大排序
versionList.Sort();
return versionList;
}
/// <summary>
/// 获取当前最大的补丁包版本号
/// </summary>
/// <returns>如果没有任何补丁版本,那么返回-1</returns>
public static int GetMaxPackageVersion(BuildTarget buildTarget, string outputRoot)
{
List<int> versionList = GetPackageVersionList(buildTarget, outputRoot);
if (versionList.Count == 0)
return -1;
return versionList[versionList.Count - 1];
}
/// <summary>
/// 是否存在任何补丁包版本
/// </summary>
public static bool HasAnyPackageVersion(BuildTarget buildTarget, string outputRoot)
{
List<int> versionList = GetPackageVersionList(buildTarget, outputRoot);
return versionList.Count > 0;
}
/// <summary>
/// 从输出目录加载补丁清单文件
/// </summary>
internal static PatchManifest LoadPatchManifestFile(string fileDirectory)
{
string filePath = $"{fileDirectory}/{YooAssetSettingsData.Setting.PatchManifestFileName}";
if (File.Exists(filePath) == false)
{
throw new System.Exception($"Not found patch manifest file : {filePath}");
}
string jsonData = FileUtility.ReadFile(filePath);
return PatchManifest.Deserialize(jsonData);
}
} }
} }

View File

@ -1,49 +0,0 @@
using System;
using UnityEngine;
namespace YooAsset.Editor
{
[CreateAssetMenu(fileName = "AssetBundleBuilderSetting", menuName = "YooAsset/Create AssetBundle Builder Settings")]
public class AssetBundleBuilderSetting : ScriptableObject
{
/// <summary>
/// 构建管线
/// </summary>
public EBuildPipeline BuildPipeline = EBuildPipeline.BuiltinBuildPipeline;
/// <summary>
/// 构建模式
/// </summary>
public EBuildMode BuildMode = EBuildMode.ForceRebuild;
/// <summary>
/// 构建的包裹名称
/// </summary>
public string BuildPackage = string.Empty;
/// <summary>
/// 压缩方式
/// </summary>
public ECompressOption CompressOption = ECompressOption.LZ4;
/// <summary>
/// 输出文件名称样式
/// </summary>
public EOutputNameStyle OutputNameStyle = EOutputNameStyle.HashName;
/// <summary>
/// 首包资源文件的拷贝方式
/// </summary>
public ECopyBuildinFileOption CopyBuildinFileOption = ECopyBuildinFileOption.None;
/// <summary>
/// 首包资源文件的标签集合
/// </summary>
public string CopyBuildinFileTags = string.Empty;
/// <summary>
/// 加密类名称
/// </summary>
public string EncyptionClassName = string.Empty;
}
}

View File

@ -1,49 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace YooAsset.Editor
{
public class AssetBundleBuilderSettingData
{
private static AssetBundleBuilderSetting _setting = null;
public static AssetBundleBuilderSetting Setting
{
get
{
if (_setting == null)
LoadSettingData();
return _setting;
}
}
/// <summary>
/// 配置数据是否被修改
/// </summary>
public static bool IsDirty { set; get; } = false;
/// <summary>
/// 加载配置文件
/// </summary>
private static void LoadSettingData()
{
_setting = SettingLoader.LoadSettingData<AssetBundleBuilderSetting>();
}
/// <summary>
/// 存储文件
/// </summary>
public static void SaveFile()
{
if (Setting != null)
{
IsDirty = false;
EditorUtility.SetDirty(Setting);
AssetDatabase.SaveAssets();
Debug.Log($"{nameof(AssetBundleBuilderSetting)}.asset is saved!");
}
}
}
}

View File

@ -12,245 +12,122 @@ namespace YooAsset.Editor
public class AssetBundleBuilderWindow : EditorWindow public class AssetBundleBuilderWindow : EditorWindow
{ {
[MenuItem("YooAsset/AssetBundle Builder", false, 102)] [MenuItem("YooAsset/AssetBundle Builder", false, 102)]
public static void OpenWindow() public static void ShowExample()
{ {
AssetBundleBuilderWindow window = GetWindow<AssetBundleBuilderWindow>("资源包构建工具", true, WindowsDefine.DockedWindowTypes); AssetBundleBuilderWindow window = GetWindow<AssetBundleBuilderWindow>();
window.titleContent = new GUIContent("资源包构建工具");
window.minSize = new Vector2(800, 600); window.minSize = new Vector2(800, 600);
} }
private BuildTarget _buildTarget; private BuildTarget _buildTarget;
private List<Type> _encryptionServicesClassTypes; private List<Type> _encryptionServicesClassTypes;
private List<string> _encryptionServicesClassNames; private List<string> _encryptionServicesClassNames;
private List<string> _buildPackageNames;
private Button _saveButton; private TextField _buildOutputTxt;
private TextField _buildOutputField; private IntegerField _buildVersionField;
private EnumField _buildPipelineField;
private EnumField _buildModeField;
private TextField _buildVersionField;
private PopupField<string> _buildPackageField;
private PopupField<string> _encryptionField;
private EnumField _compressionField; private EnumField _compressionField;
private EnumField _outputNameStyleField; private PopupField<string> _encryptionField;
private EnumField _copyBuildinFileOptionField; private Toggle _appendExtensionToggle;
private TextField _copyBuildinFileTagsField; private Toggle _forceRebuildToggle;
private TextField _buildTagsTxt;
public void CreateGUI() public void CreateGUI()
{ {
VisualElement root = this.rootVisualElement;
// 加载布局文件
string rootPath = EditorTools.GetYooAssetPath();
string uxml = $"{rootPath}/Editor/AssetBundleBuilder/{nameof(AssetBundleBuilderWindow)}.uxml";
var visualAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxml);
if (visualAsset == null)
{
Debug.LogError($"Not found {nameof(AssetBundleBuilderWindow)}.uxml : {uxml}");
return;
}
visualAsset.CloneTree(root);
try try
{ {
VisualElement root = this.rootVisualElement;
// 加载布局文件
var visualAsset = UxmlLoader.LoadWindowUXML<AssetBundleBuilderWindow>();
if (visualAsset == null)
return;
visualAsset.CloneTree(root);
// 配置保存按钮
_saveButton = root.Q<Button>("SaveButton");
_saveButton.clicked += SaveBtn_clicked;
// 构建平台
_buildTarget = EditorUserBuildSettings.activeBuildTarget; _buildTarget = EditorUserBuildSettings.activeBuildTarget;
// 包裹名称列表
_buildPackageNames = GetBuildPackageNames();
// 加密服务类
_encryptionServicesClassTypes = GetEncryptionServicesClassTypes(); _encryptionServicesClassTypes = GetEncryptionServicesClassTypes();
_encryptionServicesClassNames = _encryptionServicesClassTypes.Select(t => t.Name).ToList(); _encryptionServicesClassNames = _encryptionServicesClassTypes.Select(t => t.FullName).ToList();
// 输出目录 // 输出目录
string defaultOutputRoot = AssetBundleBuilderHelper.GetDefaultOutputRoot(); string defaultOutputRoot = AssetBundleBuilderHelper.GetDefaultOutputRoot();
_buildOutputField = root.Q<TextField>("BuildOutput"); string pipelineOutputDirectory = AssetBundleBuilderHelper.MakePipelineOutputDirectory(defaultOutputRoot, _buildTarget);
_buildOutputField.SetValueWithoutNotify(defaultOutputRoot); _buildOutputTxt = root.Q<TextField>("BuildOutput");
_buildOutputField.SetEnabled(false); _buildOutputTxt.SetValueWithoutNotify(pipelineOutputDirectory);
_buildOutputTxt.SetEnabled(false);
// 构建管线
_buildPipelineField = root.Q<EnumField>("BuildPipeline");
_buildPipelineField.Init(AssetBundleBuilderSettingData.Setting.BuildPipeline);
_buildPipelineField.SetValueWithoutNotify(AssetBundleBuilderSettingData.Setting.BuildPipeline);
_buildPipelineField.style.width = 350;
_buildPipelineField.RegisterValueChangedCallback(evt =>
{
AssetBundleBuilderSettingData.IsDirty = true;
AssetBundleBuilderSettingData.Setting.BuildPipeline = (EBuildPipeline)_buildPipelineField.value;
RefreshWindow();
});
// 构建模式
_buildModeField = root.Q<EnumField>("BuildMode");
_buildModeField.Init(AssetBundleBuilderSettingData.Setting.BuildMode);
_buildModeField.SetValueWithoutNotify(AssetBundleBuilderSettingData.Setting.BuildMode);
_buildModeField.style.width = 350;
_buildModeField.RegisterValueChangedCallback(evt =>
{
AssetBundleBuilderSettingData.IsDirty = true;
AssetBundleBuilderSettingData.Setting.BuildMode = (EBuildMode)_buildModeField.value;
RefreshWindow();
});
// 构建版本 // 构建版本
_buildVersionField = root.Q<TextField>("BuildVersion"); var appVersion = new Version(Application.version);
_buildVersionField.SetValueWithoutNotify(GetBuildPackageVersion()); _buildVersionField = root.Q<IntegerField>("BuildVersion");
_buildVersionField.SetValueWithoutNotify(appVersion.Revision);
// 构建包裹 // 压缩方式
var buildPackageContainer = root.Q("BuildPackageContainer"); _compressionField = root.Q<EnumField>("Compression");
if (_buildPackageNames.Count > 0) _compressionField.Init(ECompressOption.LZ4);
{ _compressionField.SetValueWithoutNotify(ECompressOption.LZ4);
int defaultIndex = GetDefaultPackageIndex(AssetBundleBuilderSettingData.Setting.BuildPackage); _compressionField.style.width = 300;
_buildPackageField = new PopupField<string>(_buildPackageNames, defaultIndex);
_buildPackageField.label = "Build Package";
_buildPackageField.style.width = 350;
_buildPackageField.RegisterValueChangedCallback(evt =>
{
AssetBundleBuilderSettingData.IsDirty = true;
AssetBundleBuilderSettingData.Setting.BuildPackage = _buildPackageField.value;
});
buildPackageContainer.Add(_buildPackageField);
}
else
{
_buildPackageField = new PopupField<string>();
_buildPackageField.label = "Build Package";
_buildPackageField.style.width = 350;
buildPackageContainer.Add(_buildPackageField);
}
// 加密方法 // 加密方法
var encryptionContainer = root.Q("EncryptionContainer"); var encryptionContainer = root.Q("EncryptionContainer");
if (_encryptionServicesClassNames.Count > 0) if (_encryptionServicesClassNames.Count > 0)
{ {
int defaultIndex = GetDefaultEncryptionIndex(AssetBundleBuilderSettingData.Setting.EncyptionClassName); _encryptionField = new PopupField<string>(_encryptionServicesClassNames, 0);
_encryptionField = new PopupField<string>(_encryptionServicesClassNames, defaultIndex);
_encryptionField.label = "Encryption"; _encryptionField.label = "Encryption";
_encryptionField.style.width = 350; _encryptionField.style.width = 300;
_encryptionField.RegisterValueChangedCallback(evt =>
{
AssetBundleBuilderSettingData.IsDirty = true;
AssetBundleBuilderSettingData.Setting.EncyptionClassName = _encryptionField.value;
});
encryptionContainer.Add(_encryptionField); encryptionContainer.Add(_encryptionField);
} }
else else
{ {
_encryptionField = new PopupField<string>(); _encryptionField = new PopupField<string>();
_encryptionField.label = "Encryption"; _encryptionField.label = "Encryption";
_encryptionField.style.width = 350; _encryptionField.style.width = 300;
encryptionContainer.Add(_encryptionField); encryptionContainer.Add(_encryptionField);
} }
// 压缩方式选项 // 附加后缀格式
_compressionField = root.Q<EnumField>("Compression"); _appendExtensionToggle = root.Q<Toggle>("AppendExtension");
_compressionField.Init(AssetBundleBuilderSettingData.Setting.CompressOption);
_compressionField.SetValueWithoutNotify(AssetBundleBuilderSettingData.Setting.CompressOption); // 强制构建
_compressionField.style.width = 350; _forceRebuildToggle = root.Q<Toggle>("ForceRebuild");
_compressionField.RegisterValueChangedCallback(evt => _forceRebuildToggle.SetValueWithoutNotify(true);
_forceRebuildToggle.RegisterValueChangedCallback(evt =>
{ {
AssetBundleBuilderSettingData.IsDirty = true; _buildTagsTxt.SetEnabled(_forceRebuildToggle.value);
AssetBundleBuilderSettingData.Setting.CompressOption = (ECompressOption)_compressionField.value;
}); });
// 输出文件名称样式 // 内置标签
_outputNameStyleField = root.Q<EnumField>("OutputNameStyle"); _buildTagsTxt = root.Q<TextField>("BuildinTags");
_outputNameStyleField.Init(AssetBundleBuilderSettingData.Setting.OutputNameStyle); _buildTagsTxt.SetEnabled(_forceRebuildToggle.value);
_outputNameStyleField.SetValueWithoutNotify(AssetBundleBuilderSettingData.Setting.OutputNameStyle);
_outputNameStyleField.style.width = 350;
_outputNameStyleField.RegisterValueChangedCallback(evt =>
{
AssetBundleBuilderSettingData.IsDirty = true;
AssetBundleBuilderSettingData.Setting.OutputNameStyle = (EOutputNameStyle)_outputNameStyleField.value;
});
// 首包文件拷贝选项
_copyBuildinFileOptionField = root.Q<EnumField>("CopyBuildinFileOption");
_copyBuildinFileOptionField.Init(AssetBundleBuilderSettingData.Setting.CopyBuildinFileOption);
_copyBuildinFileOptionField.SetValueWithoutNotify(AssetBundleBuilderSettingData.Setting.CopyBuildinFileOption);
_copyBuildinFileOptionField.style.width = 350;
_copyBuildinFileOptionField.RegisterValueChangedCallback(evt =>
{
AssetBundleBuilderSettingData.IsDirty = true;
AssetBundleBuilderSettingData.Setting.CopyBuildinFileOption = (ECopyBuildinFileOption)_copyBuildinFileOptionField.value;
RefreshWindow();
});
// 首包文件的资源标签
_copyBuildinFileTagsField = root.Q<TextField>("CopyBuildinFileTags");
_copyBuildinFileTagsField.SetValueWithoutNotify(AssetBundleBuilderSettingData.Setting.CopyBuildinFileTags);
_copyBuildinFileTagsField.RegisterValueChangedCallback(evt =>
{
AssetBundleBuilderSettingData.IsDirty = true;
AssetBundleBuilderSettingData.Setting.CopyBuildinFileTags = _copyBuildinFileTagsField.value;
});
// 构建按钮 // 构建按钮
var buildButton = root.Q<Button>("Build"); var buildButton = root.Q<Button>("Build");
buildButton.clicked += BuildButton_clicked; ; buildButton.clicked += BuildButton_clicked; ;
RefreshWindow();
} }
catch (Exception e) catch (Exception e)
{ {
Debug.LogError(e.ToString()); Debug.LogError(e.ToString());
} }
} }
public void OnDestroy()
{
if (AssetBundleBuilderSettingData.IsDirty)
AssetBundleBuilderSettingData.SaveFile();
}
public void Update()
{
if (_saveButton != null)
{
if (AssetBundleBuilderSettingData.IsDirty)
{
if (_saveButton.enabledSelf == false)
_saveButton.SetEnabled(true);
}
else
{
if (_saveButton.enabledSelf)
_saveButton.SetEnabled(false);
}
}
}
private void RefreshWindow() private void BuildButton_clicked()
{ {
var buildPipeline = AssetBundleBuilderSettingData.Setting.BuildPipeline; string title;
var buildMode = AssetBundleBuilderSettingData.Setting.BuildMode; string content;
var copyOption = AssetBundleBuilderSettingData.Setting.CopyBuildinFileOption; if (_forceRebuildToggle.value)
bool enableElement = buildMode == EBuildMode.ForceRebuild;
bool tagsFiledVisible = copyOption == ECopyBuildinFileOption.ClearAndCopyByTags || copyOption == ECopyBuildinFileOption.OnlyCopyByTags;
if (buildPipeline == EBuildPipeline.BuiltinBuildPipeline)
{ {
_compressionField.SetEnabled(enableElement); title = "警告";
_outputNameStyleField.SetEnabled(enableElement); content = "确定开始强制构建吗,这样会删除所有已有构建的文件";
_copyBuildinFileOptionField.SetEnabled(enableElement);
_copyBuildinFileTagsField.SetEnabled(enableElement);
} }
else else
{ {
_compressionField.SetEnabled(true); title = "提示";
_outputNameStyleField.SetEnabled(true); content = "确定开始增量构建吗";
_copyBuildinFileOptionField.SetEnabled(true);
_copyBuildinFileTagsField.SetEnabled(true);
} }
if (EditorUtility.DisplayDialog(title, content, "Yes", "No"))
_copyBuildinFileTagsField.visible = tagsFiledVisible;
}
private void SaveBtn_clicked()
{
AssetBundleBuilderSettingData.SaveFile();
}
private void BuildButton_clicked()
{
var buildMode = AssetBundleBuilderSettingData.Setting.BuildMode;
if (EditorUtility.DisplayDialog("提示", $"通过构建模式【{buildMode}】来构建!", "Yes", "No"))
{ {
EditorTools.ClearUnityConsole(); EditorTools.ClearUnityConsole();
EditorApplication.delayCall += ExecuteBuild; EditorApplication.delayCall += ExecuteBuild;
@ -268,86 +145,32 @@ namespace YooAsset.Editor
{ {
string defaultOutputRoot = AssetBundleBuilderHelper.GetDefaultOutputRoot(); string defaultOutputRoot = AssetBundleBuilderHelper.GetDefaultOutputRoot();
BuildParameters buildParameters = new BuildParameters(); BuildParameters buildParameters = new BuildParameters();
buildParameters.VerifyBuildingResult = true;
buildParameters.OutputRoot = defaultOutputRoot; buildParameters.OutputRoot = defaultOutputRoot;
buildParameters.BuildTarget = _buildTarget; buildParameters.BuildTarget = _buildTarget;
buildParameters.BuildPipeline = AssetBundleBuilderSettingData.Setting.BuildPipeline; buildParameters.BuildVersion = _buildVersionField.value;
buildParameters.BuildMode = AssetBundleBuilderSettingData.Setting.BuildMode; buildParameters.CompressOption = (ECompressOption)_compressionField.value;
buildParameters.PackageName = AssetBundleBuilderSettingData.Setting.BuildPackage; buildParameters.AppendFileExtension = _appendExtensionToggle.value;
buildParameters.PackageVersion = _buildVersionField.value;
buildParameters.VerifyBuildingResult = true;
buildParameters.AutoAnalyzeRedundancy = true;
buildParameters.ShareAssetPackRule = new DefaultShareAssetPackRule();
buildParameters.EncryptionServices = CreateEncryptionServicesInstance(); buildParameters.EncryptionServices = CreateEncryptionServicesInstance();
buildParameters.CompressOption = AssetBundleBuilderSettingData.Setting.CompressOption; buildParameters.ForceRebuild = _forceRebuildToggle.value;
buildParameters.OutputNameStyle = AssetBundleBuilderSettingData.Setting.OutputNameStyle; buildParameters.BuildinTags = _buildTagsTxt.value;
buildParameters.CopyBuildinFileOption = AssetBundleBuilderSettingData.Setting.CopyBuildinFileOption;
buildParameters.CopyBuildinFileTags = AssetBundleBuilderSettingData.Setting.CopyBuildinFileTags;
if (AssetBundleBuilderSettingData.Setting.BuildPipeline == EBuildPipeline.ScriptableBuildPipeline) AssetBundleBuilder builder = new AssetBundleBuilder();
{ builder.Run(buildParameters);
buildParameters.SBPParameters = new BuildParameters.SBPBuildParameters();
buildParameters.SBPParameters.WriteLinkXML = true;
}
var builder = new AssetBundleBuilder();
var buildResult = builder.Run(buildParameters);
if (buildResult.Success)
{
EditorUtility.RevealInFinder(buildResult.OutputPackageDirectory);
}
} }
// 构建版本相关 /// <summary>
private string GetBuildPackageVersion() /// 获取加密类的类型列表
{ /// </summary>
int totalMinutes = DateTime.Now.Hour * 60 + DateTime.Now.Minute;
return DateTime.Now.ToString("yyyy-MM-dd") + "-" + totalMinutes;
}
// 构建包裹相关
private int GetDefaultPackageIndex(string packageName)
{
for (int index = 0; index < _buildPackageNames.Count; index++)
{
if (_buildPackageNames[index] == packageName)
{
return index;
}
}
AssetBundleBuilderSettingData.IsDirty = true;
AssetBundleBuilderSettingData.Setting.BuildPackage = _buildPackageNames[0];
return 0;
}
private List<string> GetBuildPackageNames()
{
List<string> result = new List<string>();
foreach (var package in AssetBundleCollectorSettingData.Setting.Packages)
{
result.Add(package.PackageName);
}
return result;
}
// 加密类相关
private int GetDefaultEncryptionIndex(string className)
{
for (int index = 0; index < _encryptionServicesClassNames.Count; index++)
{
if (_encryptionServicesClassNames[index] == className)
{
return index;
}
}
AssetBundleBuilderSettingData.IsDirty = true;
AssetBundleBuilderSettingData.Setting.EncyptionClassName = _encryptionServicesClassNames[0];
return 0;
}
private List<Type> GetEncryptionServicesClassTypes() private List<Type> GetEncryptionServicesClassTypes()
{ {
return EditorTools.GetAssignableTypes(typeof(IEncryptionServices)); List<Type> classTypes = AssemblyUtility.GetAssignableTypes(AssemblyUtility.UnityDefaultAssemblyEditorName, typeof(IEncryptionServices));
return classTypes;
} }
/// <summary>
/// 创建加密类的实例
/// </summary>
private IEncryptionServices CreateEncryptionServicesInstance() private IEncryptionServices CreateEncryptionServicesInstance()
{ {
if (_encryptionField.index < 0) if (_encryptionField.index < 0)

View File

@ -1,18 +1,13 @@
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../UIElementsSchema/UIElements.xsd" editor-extension-mode="True"> <ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../UIElementsSchema/UIElements.xsd" editor-extension-mode="True">
<uie:Toolbar name="Toolbar" style="display: flex; flex-direction: row-reverse;"> <uie:Toolbar name="Toolbar" style="display: flex;" />
<ui:Button text="Save" display-tooltip-when-elided="true" name="SaveButton" style="background-color: rgb(56, 147, 58);" />
</uie:Toolbar>
<ui:VisualElement name="BuildContainer"> <ui:VisualElement name="BuildContainer">
<ui:TextField picking-mode="Ignore" label="Build Output" name="BuildOutput" /> <ui:TextField picking-mode="Ignore" label="Build Output" name="BuildOutput" />
<uie:EnumField label="Build Pipeline" name="BuildPipeline" /> <uie:IntegerField label="Build Version" value="0" name="BuildVersion" />
<uie:EnumField label="Build Mode" name="BuildMode" />
<ui:TextField picking-mode="Ignore" label="Build Version" name="BuildVersion" style="width: 350px;" />
<ui:VisualElement name="BuildPackageContainer" style="height: 24px;" />
<ui:VisualElement name="EncryptionContainer" style="height: 24px;" />
<uie:EnumField label="Compression" value="Center" name="Compression" /> <uie:EnumField label="Compression" value="Center" name="Compression" />
<uie:EnumField label="Output Name Style" value="Center" name="OutputNameStyle" /> <ui:VisualElement name="EncryptionContainer" style="height: 24px;" />
<uie:EnumField label="Copy Buildin File Option" value="Center" name="CopyBuildinFileOption" /> <ui:Toggle label="Append Extension" name="AppendExtension" style="height: 15px;" />
<ui:TextField picking-mode="Ignore" label="Copy Buildin File Tags" name="CopyBuildinFileTags" /> <ui:Toggle label="Force Rebuild" name="ForceRebuild" />
<ui:TextField picking-mode="Ignore" label="Buildin Tags" name="BuildinTags" />
<ui:Button text="构建" display-tooltip-when-elided="true" name="Build" style="height: 50px; background-color: rgb(40, 106, 42); margin-top: 10px;" /> <ui:Button text="构建" display-tooltip-when-elided="true" name="Build" style="height: 50px; background-color: rgb(40, 106, 42); margin-top: 10px;" />
</ui:VisualElement> </ui:VisualElement>
</ui:UXML> </ui:UXML>

View File

@ -1,37 +0,0 @@
using UnityEditor;
using UnityEngine;
namespace YooAsset.Editor
{
public static class AssetBundleSimulateBuilder
{
/// <summary>
/// 模拟构建
/// </summary>
public static string SimulateBuild(string packageName)
{
Debug.Log($"Begin to create simulate package : {packageName}");
string defaultOutputRoot = AssetBundleBuilderHelper.GetDefaultOutputRoot();
BuildParameters buildParameters = new BuildParameters();
buildParameters.OutputRoot = defaultOutputRoot;
buildParameters.BuildTarget = EditorUserBuildSettings.activeBuildTarget;
buildParameters.BuildMode = EBuildMode.SimulateBuild;
buildParameters.PackageName = packageName;
buildParameters.PackageVersion = "Simulate";
buildParameters.EnableLog = false;
AssetBundleBuilder builder = new AssetBundleBuilder();
var buildResult = builder.Run(buildParameters);
if (buildResult.Success)
{
string manifestFileName = YooAssetSettingsData.GetManifestBinaryFileName(buildParameters.PackageName, buildParameters.PackageVersion);
string manifestFilePath = $"{buildResult.OutputPackageDirectory}/{manifestFileName}";
return manifestFilePath;
}
else
{
return null;
}
}
}
}

View File

@ -1,30 +1,16 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
public class BuildAssetInfo public class BuildAssetInfo
{ {
private bool _isAddAssetTags = false;
private readonly HashSet<string> _referenceBundleNames = new HashSet<string>();
/// <summary> /// <summary>
/// 收集器类型 /// 资源包名称
/// </summary>
public ECollectorType CollectorType { private set; get; }
/// <summary>
/// 资源包完整名称
/// </summary> /// </summary>
public string BundleName { private set; get; } public string BundleName { private set; get; }
/// <summary>
/// 可寻址地址
/// </summary>
public string Address { private set; get; }
/// <summary> /// <summary>
/// 资源路径 /// 资源路径
/// </summary> /// </summary>
@ -36,20 +22,25 @@ namespace YooAsset.Editor
public bool IsRawAsset { private set; get; } public bool IsRawAsset { private set; get; }
/// <summary> /// <summary>
/// 是否为着色器资源 /// 不写入资源列表
/// </summary> /// </summary>
public bool IsShaderAsset { private set; get; } public bool NotWriteToAssetList { private set; get; }
/// <summary> /// <summary>
/// 资源的分类标签 /// 是否为主动收集资源
/// </summary>
public bool IsCollectAsset { private set; get; }
/// <summary>
/// 被依赖次数
/// </summary>
public int DependCount = 0;
/// <summary>
/// 资源分类标签列表
/// </summary> /// </summary>
public readonly List<string> AssetTags = new List<string>(); public readonly List<string> AssetTags = new List<string>();
/// <summary>
/// 资源包的分类标签
/// </summary>
public readonly List<string> BundleTags = new List<string>();
/// <summary> /// <summary>
/// 依赖的所有资源 /// 依赖的所有资源
/// 注意:包括零依赖资源和冗余资源(资源包名无效) /// 注意:包括零依赖资源和冗余资源(资源包名无效)
@ -57,35 +48,21 @@ namespace YooAsset.Editor
public List<BuildAssetInfo> AllDependAssetInfos { private set; get; } public List<BuildAssetInfo> AllDependAssetInfos { private set; get; }
public BuildAssetInfo(ECollectorType collectorType, string bundleName, string address, string assetPath, bool isRawAsset) public BuildAssetInfo(string assetPath, bool isRawAsset, bool notWriteToAssetList)
{ {
CollectorType = collectorType;
BundleName = bundleName;
Address = address;
AssetPath = assetPath; AssetPath = assetPath;
IsRawAsset = isRawAsset; IsRawAsset = isRawAsset;
NotWriteToAssetList = notWriteToAssetList;
System.Type assetType = UnityEditor.AssetDatabase.GetMainAssetTypeAtPath(assetPath); IsCollectAsset = true;
if (assetType == typeof(UnityEngine.Shader) || assetType == typeof(UnityEngine.ShaderVariantCollection))
IsShaderAsset = true;
else
IsShaderAsset = false;
} }
public BuildAssetInfo(string assetPath) public BuildAssetInfo(string assetPath)
{ {
CollectorType = ECollectorType.None;
Address = string.Empty;
AssetPath = assetPath; AssetPath = assetPath;
IsRawAsset = false; IsRawAsset = false;
NotWriteToAssetList = true;
System.Type assetType = UnityEditor.AssetDatabase.GetMainAssetTypeAtPath(assetPath); IsCollectAsset = false;
if (assetType == typeof(UnityEngine.Shader) || assetType == typeof(UnityEngine.ShaderVariantCollection))
IsShaderAsset = true;
else
IsShaderAsset = false;
} }
/// <summary> /// <summary>
/// 设置所有依赖的资源 /// 设置所有依赖的资源
/// </summary> /// </summary>
@ -98,112 +75,47 @@ namespace YooAsset.Editor
} }
/// <summary> /// <summary>
/// 添加资源的分类标签 /// 设置资源包名称
/// 说明:原始定义的资源分类标签 /// </summary>
public void SetBundleName(string bundleName)
{
if (string.IsNullOrEmpty(BundleName) == false)
throw new System.Exception("Should never get here !");
BundleName = bundleName;
}
/// <summary>
/// 添加资源分类标签
/// </summary> /// </summary>
public void AddAssetTags(List<string> tags) public void AddAssetTags(List<string> tags)
{ {
if (_isAddAssetTags)
throw new Exception("Should never get here !");
_isAddAssetTags = true;
foreach (var tag in tags) foreach (var tag in tags)
{ {
if (AssetTags.Contains(tag) == false) AddAssetTag(tag);
{
AssetTags.Add(tag);
}
} }
} }
/// <summary> /// <summary>
/// 添加资源包的分类标签 /// 添加资源分类标签
/// 说明:传染算法统计到的分类标签
/// </summary> /// </summary>
public void AddBundleTags(List<string> tags) public void AddAssetTag(string tag)
{ {
foreach (var tag in tags) if (AssetTags.Contains(tag) == false)
{ {
if (BundleTags.Contains(tag) == false) AssetTags.Add(tag);
{
BundleTags.Add(tag);
}
} }
} }
/// <summary> /// <summary>
/// 资源包名是否存在 /// 资源包名称是否有效
/// </summary> /// </summary>
public bool HasBundleName() public bool BundleNameIsValid()
{ {
if (string.IsNullOrEmpty(BundleName)) if (string.IsNullOrEmpty(BundleName))
return false; return false;
else else
return true; return true;
} }
/// <summary>
/// 添加关联的资源包名称
/// </summary>
public void AddReferenceBundleName(string bundleName)
{
if (string.IsNullOrEmpty(bundleName))
throw new Exception("Should never get here !");
if (_referenceBundleNames.Contains(bundleName) == false)
_referenceBundleNames.Add(bundleName);
}
/// <summary>
/// 计算共享资源包的完整包名
/// </summary>
public void CalculateShareBundleName(IShareAssetPackRule packRule, bool uniqueBundleName, string packageName, string shadersBundleName)
{
if (CollectorType != ECollectorType.None)
return;
if (IsRawAsset)
throw new Exception("Should never get here !");
if (IsShaderAsset)
{
BundleName = shadersBundleName;
}
else
{
if (_referenceBundleNames.Count > 1)
{
PackRuleResult packRuleResult = packRule.GetPackRuleResult(AssetPath);
BundleName = packRuleResult.GetShareBundleName(packageName, uniqueBundleName);
}
else
{
// 注意被引用次数小于1的资源不需要设置资源包名称
BundleName = string.Empty;
}
}
}
/// <summary>
/// 判断是否为冗余资源
/// </summary>
public bool IsRedundancyAsset()
{
if (CollectorType != ECollectorType.None)
return false;
if (IsRawAsset)
throw new Exception("Should never get here !");
return _referenceBundleNames.Count > 1;
}
/// <summary>
/// 获取关联资源包的数量
/// </summary>
public int GetReferenceBundleCount()
{
return _referenceBundleNames.Count;
}
} }
} }

View File

@ -8,40 +8,6 @@ namespace YooAsset.Editor
{ {
public class BuildBundleInfo public class BuildBundleInfo
{ {
public class InfoWrapper
{
/// <summary>
/// 构建内容的哈希值
/// </summary>
public string ContentHash { set; get; }
/// <summary>
/// 文件哈希值
/// </summary>
public string FileHash { set; get; }
/// <summary>
/// 文件哈希值
/// </summary>
public string FileCRC { set; get; }
/// <summary>
/// 文件哈希值
/// </summary>
public long FileSize { set; get; }
/// <summary>
/// 构建输出的文件路径
/// </summary>
public string BuildOutputFilePath { set; get; }
/// <summary>
/// 补丁包输出文件路径
/// </summary>
public string PackageOutputFilePath { set; get; }
}
/// <summary> /// <summary>
/// 资源包名称 /// 资源包名称
/// </summary> /// </summary>
@ -51,23 +17,7 @@ namespace YooAsset.Editor
/// 参与构建的资源列表 /// 参与构建的资源列表
/// 注意:不包含零依赖资源 /// 注意:不包含零依赖资源
/// </summary> /// </summary>
public readonly List<BuildAssetInfo> AllMainAssets = new List<BuildAssetInfo>(); public readonly List<BuildAssetInfo> BuildinAssets = new List<BuildAssetInfo>();
/// <summary>
/// 补丁文件信息
/// </summary>
public readonly InfoWrapper BundleInfo = new InfoWrapper();
/// <summary>
/// Bundle文件的加载方法
/// </summary>
public EBundleLoadMethod LoadMethod { set; get; }
/// <summary>
/// 加密生成文件的路径
/// 注意:如果未加密该路径为空
/// </summary>
public string EncryptedFilePath { set; get; }
/// <summary> /// <summary>
/// 是否为原生文件 /// 是否为原生文件
@ -76,29 +26,15 @@ namespace YooAsset.Editor
{ {
get get
{ {
foreach (var assetInfo in AllMainAssets) foreach (var asset in BuildinAssets)
{ {
if (assetInfo.IsRawAsset) if (asset.IsRawAsset)
return true; return true;
} }
return false; return false;
} }
} }
/// <summary>
/// 是否为加密文件
/// </summary>
public bool IsEncryptedFile
{
get
{
if (string.IsNullOrEmpty(EncryptedFilePath))
return false;
else
return true;
}
}
public BuildBundleInfo(string bundleName) public BuildBundleInfo(string bundleName)
{ {
@ -113,7 +49,7 @@ namespace YooAsset.Editor
if (IsContainsAsset(assetInfo.AssetPath)) if (IsContainsAsset(assetInfo.AssetPath))
throw new System.Exception($"Asset is existed : {assetInfo.AssetPath}"); throw new System.Exception($"Asset is existed : {assetInfo.AssetPath}");
AllMainAssets.Add(assetInfo); BuildinAssets.Add(assetInfo);
} }
/// <summary> /// <summary>
@ -121,7 +57,7 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public bool IsContainsAsset(string assetPath) public bool IsContainsAsset(string assetPath)
{ {
foreach (var assetInfo in AllMainAssets) foreach (var assetInfo in BuildinAssets)
{ {
if (assetInfo.AssetPath == assetPath) if (assetInfo.AssetPath == assetPath)
{ {
@ -132,14 +68,14 @@ namespace YooAsset.Editor
} }
/// <summary> /// <summary>
/// 获取资源包的分类标签列表 /// 获取资源标签列表
/// </summary> /// </summary>
public string[] GetBundleTags() public string[] GetAssetTags()
{ {
List<string> result = new List<string>(AllMainAssets.Count); List<string> result = new List<string>(BuildinAssets.Count);
foreach (var assetInfo in AllMainAssets) foreach (var assetInfo in BuildinAssets)
{ {
foreach (var assetTag in assetInfo.BundleTags) foreach (var assetTag in assetInfo.AssetTags)
{ {
if (result.Contains(assetTag) == false) if (result.Contains(assetTag) == false)
result.Add(assetTag); result.Add(assetTag);
@ -149,42 +85,27 @@ namespace YooAsset.Editor
} }
/// <summary> /// <summary>
/// 获取该资源包内的所有资源(包括零依赖资源) /// 获取文件的扩展名
/// </summary> /// </summary>
public List<string> GetAllBuiltinAssetPaths() public string GetAppendExtension()
{ {
var packAssets = GetAllMainAssetPaths(); return System.IO.Path.GetExtension(BundleName);
List<string> result = new List<string>(packAssets);
foreach (var assetInfo in AllMainAssets)
{
if (assetInfo.AllDependAssetInfos == null)
continue;
foreach (var dependAssetInfo in assetInfo.AllDependAssetInfos)
{
if (dependAssetInfo.HasBundleName() == false)
{
if (result.Contains(dependAssetInfo.AssetPath) == false)
result.Add(dependAssetInfo.AssetPath);
}
}
}
return result;
} }
/// <summary> /// <summary>
/// 获取构建的资源路径列表 /// 获取构建的资源路径列表
/// </summary> /// </summary>
public string[] GetAllMainAssetPaths() public string[] GetBuildinAssetPaths()
{ {
return AllMainAssets.Select(t => t.AssetPath).ToArray(); return BuildinAssets.Select(t => t.AssetPath).ToArray();
} }
/// <summary> /// <summary>
/// 获取所有写入补丁清单的资源 /// 获取所有写入补丁清单的资源
/// </summary> /// </summary>
public BuildAssetInfo[] GetAllMainAssetInfos() public BuildAssetInfo[] GetAllPatchAssetInfos()
{ {
return AllMainAssets.Where(t => t.CollectorType == ECollectorType.MainAssetCollector).ToArray(); return BuildinAssets.Where(t => t.IsCollectAsset && t.NotWriteToAssetList == false).ToArray();
} }
/// <summary> /// <summary>
@ -196,24 +117,8 @@ namespace YooAsset.Editor
AssetBundleBuild build = new AssetBundleBuild(); AssetBundleBuild build = new AssetBundleBuild();
build.assetBundleName = BundleName; build.assetBundleName = BundleName;
build.assetBundleVariant = string.Empty; build.assetBundleVariant = string.Empty;
build.assetNames = GetAllMainAssetPaths(); build.assetNames = GetBuildinAssetPaths();
return build; return build;
} }
/// <summary>
/// 创建PackageBundle类
/// </summary>
internal PackageBundle CreatePackageBundle()
{
PackageBundle packageBundle = new PackageBundle();
packageBundle.BundleName = BundleName;
packageBundle.FileHash = BundleInfo.FileHash;
packageBundle.FileCRC = BundleInfo.FileCRC;
packageBundle.FileSize = BundleInfo.FileSize;
packageBundle.IsRawFile = IsRawFile;
packageBundle.LoadMethod = (byte)LoadMethod;
packageBundle.Tags = GetBundleTags();
return packageBundle;
}
} }
} }

View File

@ -8,13 +8,6 @@ namespace YooAsset.Editor
{ {
public class BuildMapContext : IContextObject public class BuildMapContext : IContextObject
{ {
private readonly Dictionary<string, BuildBundleInfo> _bundleInfoDic = new Dictionary<string, BuildBundleInfo>(10000);
/// <summary>
/// 冗余的资源列表
/// </summary>
public readonly List<ReportRedundancyInfo> RedundancyInfos= new List<ReportRedundancyInfo>(1000);
/// <summary> /// <summary>
/// 参与构建的资源总数 /// 参与构建的资源总数
/// 说明:包括主动收集的资源以及其依赖的所有资源 /// 说明:包括主动收集的资源以及其依赖的所有资源
@ -22,30 +15,9 @@ namespace YooAsset.Editor
public int AssetFileCount; public int AssetFileCount;
/// <summary> /// <summary>
/// 是否启用可寻址资源定位 /// 资源包列表
/// </summary> /// </summary>
public bool EnableAddressable; public readonly List<BuildBundleInfo> BundleInfos = new List<BuildBundleInfo>(1000);
/// <summary>
/// 资源包名唯一化
/// </summary>
public bool UniqueBundleName;
/// <summary>
/// 着色器统一的全名称
/// </summary>
public string ShadersBundleName;
/// <summary>
/// 资源包信息列表
/// </summary>
public Dictionary<string, BuildBundleInfo>.ValueCollection Collection
{
get
{
return _bundleInfoDic.Values;
}
}
/// <summary> /// <summary>
@ -53,40 +25,53 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public void PackAsset(BuildAssetInfo assetInfo) public void PackAsset(BuildAssetInfo assetInfo)
{ {
string bundleName = assetInfo.BundleName; if (TryGetBundleInfo(assetInfo.BundleName, out BuildBundleInfo bundleInfo))
if (string.IsNullOrEmpty(bundleName))
throw new Exception("Should never get here !");
if (_bundleInfoDic.TryGetValue(bundleName, out BuildBundleInfo bundleInfo))
{ {
bundleInfo.PackAsset(assetInfo); bundleInfo.PackAsset(assetInfo);
} }
else else
{ {
BuildBundleInfo newBundleInfo = new BuildBundleInfo(bundleName); BuildBundleInfo newBundleInfo = new BuildBundleInfo(assetInfo.BundleName);
newBundleInfo.PackAsset(assetInfo); newBundleInfo.PackAsset(assetInfo);
_bundleInfoDic.Add(bundleName, newBundleInfo); BundleInfos.Add(newBundleInfo);
} }
} }
/// <summary> /// <summary>
/// 是否包含资源包 /// 获取所有的打包资源
/// </summary> /// </summary>
public bool IsContainsBundle(string bundleName) public List<BuildAssetInfo> GetAllAssets()
{ {
return _bundleInfoDic.ContainsKey(bundleName); List<BuildAssetInfo> result = new List<BuildAssetInfo>(BundleInfos.Count);
} foreach (var bundleInfo in BundleInfos)
/// <summary>
/// 获取资源包信息如果没找到返回NULL
/// </summary>
public BuildBundleInfo GetBundleInfo(string bundleName)
{
if (_bundleInfoDic.TryGetValue(bundleName, out BuildBundleInfo result))
{ {
return result; result.AddRange(bundleInfo.BuildinAssets);
} }
throw new Exception($"Not found bundle : {bundleName}"); return result;
}
/// <summary>
/// 获取AssetBundle内包含的标记列表
/// </summary>
public string[] GetAssetTags(string bundleName)
{
if (TryGetBundleInfo(bundleName, out BuildBundleInfo bundleInfo))
{
return bundleInfo.GetAssetTags();
}
throw new Exception($"Not found {nameof(BuildBundleInfo)} : {bundleName}");
}
/// <summary>
/// 获取AssetBundle内构建的资源路径列表
/// </summary>
public string[] GetBuildinAssetPaths(string bundleName)
{
if (TryGetBundleInfo(bundleName, out BuildBundleInfo bundleInfo))
{
return bundleInfo.GetBuildinAssetPaths();
}
throw new Exception($"Not found {nameof(BuildBundleInfo)} : {bundleName}");
} }
/// <summary> /// <summary>
@ -94,8 +79,8 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public UnityEditor.AssetBundleBuild[] GetPipelineBuilds() public UnityEditor.AssetBundleBuild[] GetPipelineBuilds()
{ {
List<UnityEditor.AssetBundleBuild> builds = new List<UnityEditor.AssetBundleBuild>(_bundleInfoDic.Count); List<UnityEditor.AssetBundleBuild> builds = new List<UnityEditor.AssetBundleBuild>(BundleInfos.Count);
foreach (var bundleInfo in _bundleInfoDic.Values) foreach (var bundleInfo in BundleInfos)
{ {
if (bundleInfo.IsRawFile == false) if (bundleInfo.IsRawFile == false)
builds.Add(bundleInfo.CreatePipelineBuild()); builds.Add(bundleInfo.CreatePipelineBuild());
@ -104,15 +89,25 @@ namespace YooAsset.Editor
} }
/// <summary> /// <summary>
/// 创建着色器信息类 /// 是否包含资源包
/// </summary> /// </summary>
public void CreateShadersBundleInfo(string shadersBundleName) public bool IsContainsBundle(string bundleName)
{ {
if (IsContainsBundle(shadersBundleName) == false) return TryGetBundleInfo(bundleName, out BuildBundleInfo bundleInfo);
}
public bool TryGetBundleInfo(string bundleName, out BuildBundleInfo result)
{
foreach (var bundleInfo in BundleInfos)
{ {
var shaderBundleInfo = new BuildBundleInfo(shadersBundleName); if (bundleInfo.BundleName == bundleName)
_bundleInfoDic.Add(shadersBundleName, shaderBundleInfo); {
result = bundleInfo;
return true;
}
} }
result = null;
return false;
} }
} }
} }

View File

@ -0,0 +1,113 @@
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset.Editor
{
public static class BuildMapHelper
{
/// <summary>
/// 执行资源构建上下文
/// </summary>
public static BuildMapContext SetupBuildMap()
{
BuildMapContext context = new BuildMapContext();
Dictionary<string, BuildAssetInfo> buildAssetDic = new Dictionary<string, BuildAssetInfo>();
// 0. 检测配置合法性
AssetBundleGrouperSettingData.Setting.CheckConfigError();
// 1. 获取主动收集的资源
List<CollectAssetInfo> collectAssetInfos = AssetBundleGrouperSettingData.Setting.GetAllCollectAssets();
// 2. 录入主动收集的资源
foreach (var collectAssetInfo in collectAssetInfos)
{
if (buildAssetDic.ContainsKey(collectAssetInfo.AssetPath) == false)
{
var buildAssetInfo = new BuildAssetInfo(collectAssetInfo.AssetPath, collectAssetInfo.IsRawAsset, collectAssetInfo.NotWriteToAssetList);
buildAssetInfo.SetBundleName(collectAssetInfo.BundleName);
buildAssetInfo.AddAssetTags(collectAssetInfo.AssetTags);
buildAssetDic.Add(collectAssetInfo.AssetPath, buildAssetInfo);
}
else
{
throw new Exception($"Should never get here !");
}
}
// 3. 录入并分析依赖资源
foreach (var collectAssetInfo in collectAssetInfos)
{
foreach (var dependAssetPath in collectAssetInfo.DependAssets)
{
if (buildAssetDic.ContainsKey(dependAssetPath))
{
buildAssetDic[dependAssetPath].DependCount++;
buildAssetDic[dependAssetPath].AddAssetTags(collectAssetInfo.AssetTags);
}
else
{
var buildAssetInfo = new BuildAssetInfo(dependAssetPath);
buildAssetInfo.AddAssetTags(collectAssetInfo.AssetTags);
buildAssetDic.Add(dependAssetPath, buildAssetInfo);
}
}
}
context.AssetFileCount = buildAssetDic.Count;
// 4. 设置主动收集资源的依赖列表
foreach (var collectAssetInfo in collectAssetInfos)
{
var dependAssetInfos = new List<BuildAssetInfo>(collectAssetInfo.DependAssets.Count);
foreach (var dependAssetPath in collectAssetInfo.DependAssets)
{
if (buildAssetDic.TryGetValue(dependAssetPath, out BuildAssetInfo value))
dependAssetInfos.Add(value);
else
throw new Exception("Should never get here !");
}
buildAssetDic[collectAssetInfo.AssetPath].SetAllDependAssetInfos(dependAssetInfos);
}
// 5. 移除零依赖的资源
List<BuildAssetInfo> removeList = new List<BuildAssetInfo>();
foreach (KeyValuePair<string, BuildAssetInfo> pair in buildAssetDic)
{
var buildAssetInfo = pair.Value;
if (buildAssetInfo.IsCollectAsset)
continue;
if (buildAssetInfo.DependCount == 0)
removeList.Add(buildAssetInfo);
}
foreach (var removeValue in removeList)
{
buildAssetDic.Remove(removeValue.AssetPath);
}
// 6. 设置未命名的资源包
IPackRule defaultPackRule = new PackDirectory();
foreach (KeyValuePair<string, BuildAssetInfo> pair in buildAssetDic)
{
var buildAssetInfo = pair.Value;
if (buildAssetInfo.BundleNameIsValid() == false)
{
string bundleName = defaultPackRule.GetBundleName(new PackRuleData(buildAssetInfo.AssetPath));
bundleName = AssetBundleCollector.RevisedBundleName(bundleName, false);
buildAssetInfo.SetBundleName(bundleName);
}
}
// 7. 构建资源包
var allBuildAssets = buildAssetDic.Values.ToList();
if (allBuildAssets.Count == 0)
throw new Exception("构建的资源列表不能为空");
foreach (var assetInfo in allBuildAssets)
{
context.PackAsset(assetInfo);
}
return context;
}
}
}

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: f94918fa1ea63c34fa0e49fdad4119cf guid: e9274735f1f14af4b893c21a4240b816
MonoImporter: MonoImporter:
externalObjects: {} externalObjects: {}
serializedVersion: 2 serializedVersion: 2

View File

@ -10,31 +10,9 @@ namespace YooAsset.Editor
public class BuildParameters public class BuildParameters
{ {
/// <summary> /// <summary>
/// SBP构建参数 /// 验证构建结果
/// </summary> /// </summary>
public class SBPBuildParameters public bool VerifyBuildingResult = false;
{
/// <summary>
/// 生成代码防裁剪配置
/// </summary>
public bool WriteLinkXML = true;
/// <summary>
/// 缓存服务器地址
/// </summary>
public string CacheServerHost;
/// <summary>
/// 缓存服务器端口
/// </summary>
public int CacheServerPort;
}
/// <summary>
/// 可编程构建管线的参数
/// </summary>
public SBPBuildParameters SBPParameters;
/// <summary> /// <summary>
/// 输出的根目录 /// 输出的根目录
@ -47,70 +25,47 @@ namespace YooAsset.Editor
public BuildTarget BuildTarget; public BuildTarget BuildTarget;
/// <summary> /// <summary>
/// 构建管线 /// 构建的版本(资源版本号)
/// </summary> /// </summary>
public EBuildPipeline BuildPipeline; public int BuildVersion;
/// <summary> /// <summary>
/// 构建模式 /// 启用自动分包机制
/// 说明:自动分包机制可以实现资源零冗余
/// </summary> /// </summary>
public EBuildMode BuildMode; public bool EnableAutoCollect = true;
/// <summary> /// <summary>
/// 构建的包裹名称 /// 追加文件扩展名
/// </summary> /// </summary>
public string PackageName; public bool AppendFileExtension = false;
/// <summary> /// <summary>
/// 构建的包裹版本 /// 加密类
/// </summary> /// </summary>
public string PackageVersion; public IEncryptionServices EncryptionServices;
/// <summary> /// <summary>
/// 是否显示普通日志 /// 强制重新构建整个项目如果为FALSE则是增量打包
/// </summary> /// </summary>
public bool EnableLog = true; public bool ForceRebuild;
/// <summary> /// <summary>
/// 验证构建结果 /// 内置资源的标记列表
/// 注意:分号为分隔符
/// </summary> /// </summary>
public bool VerifyBuildingResult = false; public string BuildinTags;
/// <summary>
/// 自动分析冗余资源
/// </summary>
public bool AutoAnalyzeRedundancy = true;
/// <summary>
/// 共享资源的打包规则
/// </summary>
public IShareAssetPackRule ShareAssetPackRule = null;
/// <summary>
/// 资源的加密接口
/// </summary>
public IEncryptionServices EncryptionServices = null;
/// <summary>
/// 补丁文件名称的样式
/// </summary>
public EOutputNameStyle OutputNameStyle = EOutputNameStyle.HashName;
/// <summary>
/// 拷贝内置资源选项
/// </summary>
public ECopyBuildinFileOption CopyBuildinFileOption = ECopyBuildinFileOption.None;
/// <summary>
/// 拷贝内置资源的标签
/// </summary>
public string CopyBuildinFileTags = string.Empty;
/// <summary> /// <summary>
/// 压缩选项 /// 压缩选项
/// </summary> /// </summary>
public ECompressOption CompressOption = ECompressOption.Uncompressed; public ECompressOption CompressOption;
/// <summary>
/// 文件名附加上哈希值
/// </summary>
public bool AppendHash = false;
/// <summary> /// <summary>
/// 禁止写入类型树结构(可以降低包体和内存并提高加载效率) /// 禁止写入类型树结构(可以降低包体和内存并提高加载效率)
@ -121,5 +76,19 @@ namespace YooAsset.Editor
/// 忽略类型树变化 /// 忽略类型树变化
/// </summary> /// </summary>
public bool IgnoreTypeTreeChanges = true; public bool IgnoreTypeTreeChanges = true;
/// <summary>
/// 禁用名称查找资源(可以降内存并提高加载效率)
/// </summary>
public bool DisableLoadAssetByFileName = false;
/// <summary>
/// 获取内置标记列表
/// </summary>
public List<string> GetBuildinTags()
{
return StringUtility.StringToStringList(BuildinTags, ';');
}
} }
} }

View File

@ -1,119 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
namespace YooAsset.Editor
{
public class BuildParametersContext : IContextObject
{
private string _pipelineOutputDirectory = string.Empty;
private string _packageOutputDirectory = string.Empty;
/// <summary>
/// 构建参数
/// </summary>
public BuildParameters Parameters { private set; get; }
public BuildParametersContext(BuildParameters parameters)
{
Parameters = parameters;
}
/// <summary>
/// 获取构建管线的输出目录
/// </summary>
/// <returns></returns>
public string GetPipelineOutputDirectory()
{
if (string.IsNullOrEmpty(_pipelineOutputDirectory))
{
_pipelineOutputDirectory = $"{Parameters.OutputRoot}/{Parameters.BuildTarget}/{Parameters.PackageName}/{YooAssetSettings.OutputFolderName}";
}
return _pipelineOutputDirectory;
}
/// <summary>
/// 获取本次构建的补丁目录
/// </summary>
public string GetPackageOutputDirectory()
{
if (string.IsNullOrEmpty(_packageOutputDirectory))
{
_packageOutputDirectory = $"{Parameters.OutputRoot}/{Parameters.BuildTarget}/{Parameters.PackageName}/{Parameters.PackageVersion}";
}
return _packageOutputDirectory;
}
/// <summary>
/// 获取内置构建管线的构建选项
/// </summary>
public BuildAssetBundleOptions GetPipelineBuildOptions()
{
// For the new build system, unity always need BuildAssetBundleOptions.CollectDependencies and BuildAssetBundleOptions.DeterministicAssetBundle
// 除非设置ForceRebuildAssetBundle标记否则会进行增量打包
if (Parameters.BuildMode == EBuildMode.SimulateBuild)
throw new Exception("Should never get here !");
BuildAssetBundleOptions opt = BuildAssetBundleOptions.None;
opt |= BuildAssetBundleOptions.StrictMode; //Do not allow the build to succeed if any errors are reporting during it.
if (Parameters.BuildMode == EBuildMode.DryRunBuild)
{
opt |= BuildAssetBundleOptions.DryRunBuild;
return opt;
}
if (Parameters.CompressOption == ECompressOption.Uncompressed)
opt |= BuildAssetBundleOptions.UncompressedAssetBundle;
else if (Parameters.CompressOption == ECompressOption.LZ4)
opt |= BuildAssetBundleOptions.ChunkBasedCompression;
if (Parameters.BuildMode == EBuildMode.ForceRebuild)
opt |= BuildAssetBundleOptions.ForceRebuildAssetBundle; //Force rebuild the asset bundles
if (Parameters.DisableWriteTypeTree)
opt |= BuildAssetBundleOptions.DisableWriteTypeTree; //Do not include type information within the asset bundle (don't write type tree).
if (Parameters.IgnoreTypeTreeChanges)
opt |= BuildAssetBundleOptions.IgnoreTypeTreeChanges; //Ignore the type tree changes when doing the incremental build check.
opt |= BuildAssetBundleOptions.DisableLoadAssetByFileName; //Disables Asset Bundle LoadAsset by file name.
opt |= BuildAssetBundleOptions.DisableLoadAssetByFileNameWithExtension; //Disables Asset Bundle LoadAsset by file name with extension.
return opt;
}
/// <summary>
/// 获取可编程构建管线的构建参数
/// </summary>
public UnityEditor.Build.Pipeline.BundleBuildParameters GetSBPBuildParameters()
{
if (Parameters.BuildMode == EBuildMode.SimulateBuild)
throw new Exception("Should never get here !");
var targetGroup = BuildPipeline.GetBuildTargetGroup(Parameters.BuildTarget);
var pipelineOutputDirectory = GetPipelineOutputDirectory();
var buildParams = new UnityEditor.Build.Pipeline.BundleBuildParameters(Parameters.BuildTarget, targetGroup, pipelineOutputDirectory);
if (Parameters.CompressOption == ECompressOption.Uncompressed)
buildParams.BundleCompression = UnityEngine.BuildCompression.Uncompressed;
else if (Parameters.CompressOption == ECompressOption.LZMA)
buildParams.BundleCompression = UnityEngine.BuildCompression.LZMA;
else if (Parameters.CompressOption == ECompressOption.LZ4)
buildParams.BundleCompression = UnityEngine.BuildCompression.LZ4;
else
throw new System.NotImplementedException(Parameters.CompressOption.ToString());
if (Parameters.DisableWriteTypeTree)
buildParams.ContentBuildFlags |= UnityEditor.Build.Content.ContentBuildFlags.DisableWriteTypeTree;
buildParams.UseCache = true;
buildParams.CacheServerHost = Parameters.SBPParameters.CacheServerHost;
buildParams.CacheServerPort = Parameters.SBPParameters.CacheServerPort;
buildParams.WriteLinkXML = Parameters.SBPParameters.WriteLinkXML;
return buildParams;
}
}
}

View File

@ -1,7 +1,6 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using UnityEngine; using UnityEngine;
namespace YooAsset.Editor namespace YooAsset.Editor
@ -27,11 +26,6 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public List<ReportBundleInfo> BundleInfos = new List<ReportBundleInfo>(); public List<ReportBundleInfo> BundleInfos = new List<ReportBundleInfo>();
/// <summary>
/// 冗余的资源列表
/// </summary>
public List<ReportRedundancyInfo> RedundancyInfos = new List<ReportRedundancyInfo>();
/// <summary> /// <summary>
/// 获取资源包信息类 /// 获取资源包信息类
@ -62,11 +56,8 @@ namespace YooAsset.Editor
public static void Serialize(string savePath, BuildReport buildReport) public static void Serialize(string savePath, BuildReport buildReport)
{ {
if (File.Exists(savePath))
File.Delete(savePath);
string json = JsonUtility.ToJson(buildReport, true); string json = JsonUtility.ToJson(buildReport, true);
FileUtility.WriteAllText(savePath, json); FileUtility.CreateFile(savePath, json);
} }
public static BuildReport Deserialize(string jsonData) public static BuildReport Deserialize(string jsonData)
{ {

View File

@ -7,36 +7,15 @@ namespace YooAsset.Editor
[Serializable] [Serializable]
public class ReportAssetInfo public class ReportAssetInfo
{ {
/// <summary>
/// 可寻址地址
/// </summary>
public string Address;
/// <summary> /// <summary>
/// 资源路径 /// 资源路径
/// </summary> /// </summary>
public string AssetPath; public string AssetPath;
/// <summary>
/// 资源GUID
/// 说明Meta文件记录的GUID
/// </summary>
public string AssetGUID;
/// <summary>
/// 资源的分类标签
/// </summary>
public string[] AssetTags;
/// <summary> /// <summary>
/// 所属资源包名称 /// 所属资源包名称
/// </summary> /// </summary>
public string MainBundleName; public string MainBundle;
/// <summary>
/// 所属资源包的大小
/// </summary>
public long MainBundleSize;
/// <summary> /// <summary>
/// 依赖的资源包名称列表 /// 依赖的资源包名称列表

View File

@ -1,5 +1,4 @@
using System; using System;
using System.Linq;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
@ -14,34 +13,24 @@ namespace YooAsset.Editor
public string BundleName; public string BundleName;
/// <summary> /// <summary>
/// 文件名称 /// 哈希值
/// </summary> /// </summary>
public string FileName; public string Hash;
/// <summary>
/// 文件哈希值
/// </summary>
public string FileHash;
/// <summary> /// <summary>
/// 文件校验码 /// 文件校验码
/// </summary> /// </summary>
public string FileCRC; public string CRC;
/// <summary> /// <summary>
/// 文件大小(字节数) /// 文件大小(字节数)
/// </summary> /// </summary>
public long FileSize; public long SizeBytes;
/// <summary> /// <summary>
/// 是否为原生文件 /// 文件版本
/// </summary> /// </summary>
public bool IsRawFile; public int Version;
/// <summary>
/// 加载方法
/// </summary>
public EBundleLoadMethod LoadMethod;
/// <summary> /// <summary>
/// Tags /// Tags
@ -49,24 +38,8 @@ namespace YooAsset.Editor
public string[] Tags; public string[] Tags;
/// <summary> /// <summary>
/// 引用该资源包的ID列表 /// Flags
/// </summary> /// </summary>
public int[] ReferenceIDs; public int Flags;
/// <summary>
/// 该资源包内包含的所有资源
/// </summary>
public List<string> AllBuiltinAssets = new List<string>();
/// <summary>
/// 获取资源分类标签的字符串
/// </summary>
public string GetTagsString()
{
if (Tags != null)
return String.Join(";", Tags);
else
return string.Empty;
}
} }
} }

View File

@ -1,36 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset.Editor
{
[Serializable]
public class ReportRedundancyInfo
{
/// <summary>
/// 资源路径
/// </summary>
public string AssetPath;
/// <summary>
/// 资源类型
/// </summary>
public string AssetType;
/// <summary>
/// 资源GUID
/// 说明Meta文件记录的GUID
/// </summary>
public string AssetGUID;
/// <summary>
/// 资源文件大小
/// </summary>
public long FileSize;
/// <summary>
/// 冗余的资源包数量
/// </summary>
public int Number;
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 7fbb7b27f54d3b0439a951348fd9d785
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -8,11 +8,6 @@ namespace YooAsset.Editor
[Serializable] [Serializable]
public class ReportSummary public class ReportSummary
{ {
/// <summary>
/// YooAsset版本
/// </summary>
public string YooVersion;
/// <summary> /// <summary>
/// 引擎版本 /// 引擎版本
/// </summary> /// </summary>
@ -21,7 +16,7 @@ namespace YooAsset.Editor
/// <summary> /// <summary>
/// 构建时间 /// 构建时间
/// </summary> /// </summary>
public string BuildDate; public string BuildTime;
/// <summary> /// <summary>
/// 构建耗时(单位:秒) /// 构建耗时(单位:秒)
@ -34,44 +29,29 @@ namespace YooAsset.Editor
public BuildTarget BuildTarget; public BuildTarget BuildTarget;
/// <summary> /// <summary>
/// 构建管线 /// 构建版本
/// </summary> /// </summary>
public EBuildPipeline BuildPipeline; public int BuildVersion;
/// <summary> /// <summary>
/// 构建模式 /// 启用自动分包机制
/// </summary> /// </summary>
public EBuildMode BuildMode; public bool EnableAutoCollect;
/// <summary> /// <summary>
/// 构建包裹名称 /// 追加文件扩展名
/// </summary> /// </summary>
public string BuildPackageName; public bool AppendFileExtension;
/// <summary> /// <summary>
/// 构建包裹版本 /// 自动收集着色器
/// </summary> /// </summary>
public string BuildPackageVersion; public bool AutoCollectShaders;
/// <summary> /// <summary>
/// 启用可寻址资源定位 /// 自动收集的着色器资源包名称
/// </summary> /// </summary>
public bool EnableAddressable; public string ShadersBundleName;
/// <summary>
/// 资源包名唯一化
/// </summary>
public bool UniqueBundleName;
/// <summary>
/// 自动分析冗余
/// </summary>
public bool AutoAnalyzeRedundancy;
/// <summary>
/// 共享资源的打包类名称
/// </summary>
public string ShareAssetPackRuleClassName;
/// <summary> /// <summary>
/// 加密服务类名称 /// 加密服务类名称
@ -79,16 +59,20 @@ namespace YooAsset.Editor
public string EncryptionServicesClassName; public string EncryptionServicesClassName;
// 构建参数 // 构建参数
public EOutputNameStyle OutputNameStyle; public bool ForceRebuild;
public string BuildinTags;
public ECompressOption CompressOption; public ECompressOption CompressOption;
public bool AppendHash;
public bool DisableWriteTypeTree; public bool DisableWriteTypeTree;
public bool IgnoreTypeTreeChanges; public bool IgnoreTypeTreeChanges;
public bool DisableLoadAssetByFileName;
// 构建结果 // 构建结果
public int AssetFileTotalCount; public int AssetFileTotalCount;
public int MainAssetTotalCount;
public int AllBundleTotalCount; public int AllBundleTotalCount;
public long AllBundleTotalSize; public long AllBundleTotalSize;
public int BuildinBundleTotalCount;
public long BuildinBundleTotalSize;
public int EncryptedBundleTotalCount; public int EncryptedBundleTotalCount;
public long EncryptedBundleTotalSize; public long EncryptedBundleTotalSize;
public int RawBundleTotalCount; public int RawBundleTotalCount;

View File

@ -1,33 +0,0 @@
using System;
using System.IO;
using System.Collections.Generic;
using UnityEngine;
namespace YooAsset.Editor
{
public static class BuildLogger
{
private static bool _enableLog = true;
public static void InitLogger(bool enableLog)
{
_enableLog = enableLog;
}
public static void Log(string message)
{
if (_enableLog)
{
Debug.Log(message);
}
}
public static void Warning(string message)
{
Debug.LogWarning(message);
}
public static void Error(string message)
{
Debug.LogError(message);
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 2bc82466a51f50141975e4424095aa09
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,29 +0,0 @@

namespace YooAsset.Editor
{
/// <summary>
/// 构建结果
/// </summary>
public class BuildResult
{
/// <summary>
/// 构建是否成功
/// </summary>
public bool Success;
/// <summary>
/// 构建失败的任务
/// </summary>
public string FailedTask;
/// <summary>
/// 构建失败的信息
/// </summary>
public string ErrorInfo;
/// <summary>
/// 输出的补丁包目录
/// </summary>
public string OutputPackageDirectory;
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: e0855c4b5eaa26942bd7ad177fe3c288
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,72 +1,41 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection;
using System.Diagnostics;
using UnityEngine; using UnityEngine;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
public class BuildRunner public class BuildRunner
{ {
private static Stopwatch _buildWatch;
/// <summary>
/// 总耗时
/// </summary>
public static int TotalSeconds = 0;
/// <summary> /// <summary>
/// 执行构建流程 /// 执行构建流程
/// </summary> /// </summary>
/// <returns>如果成功返回TRUE否则返回FALSE</returns> /// <returns>如果成功返回TRUE否则返回FALSE</returns>
public static BuildResult Run(List<IBuildTask> pipeline, BuildContext context) public static bool Run(List<IBuildTask> pipeline, BuildContext context)
{ {
if (pipeline == null) if (pipeline == null)
throw new ArgumentNullException("pipeline"); throw new ArgumentNullException("pipeline");
if (context == null) if (context == null)
throw new ArgumentNullException("context"); throw new ArgumentNullException("context");
BuildResult buildResult = new BuildResult(); bool succeed = true;
buildResult.Success = true;
TotalSeconds = 0;
for (int i = 0; i < pipeline.Count; i++) for (int i = 0; i < pipeline.Count; i++)
{ {
IBuildTask task = pipeline[i]; IBuildTask task = pipeline[i];
try try
{ {
_buildWatch = Stopwatch.StartNew();
var taskAttribute = task.GetType().GetCustomAttribute<TaskAttribute>();
if (taskAttribute != null)
BuildLogger.Log($"---------------------------------------->{taskAttribute.Desc}<---------------------------------------");
task.Run(context); task.Run(context);
_buildWatch.Stop();
// 统计耗时
int seconds = GetBuildSeconds();
TotalSeconds += seconds;
if (taskAttribute != null)
BuildLogger.Log($"{taskAttribute.Desc}耗时:{seconds}秒");
} }
catch (Exception e) catch (Exception e)
{ {
EditorTools.ClearProgressBar(); Debug.LogError($"Build task {task.GetType().Name} failed : {e}");
buildResult.FailedTask = task.GetType().Name; succeed = false;
buildResult.ErrorInfo = e.ToString();
buildResult.Success = false;
break; break;
} }
} }
// 返回运行结果 // 返回运行结果
BuildLogger.Log($"构建过程总计耗时:{TotalSeconds}秒"); return succeed;
return buildResult;
}
private static int GetBuildSeconds()
{
float seconds = _buildWatch.ElapsedMilliseconds / 1000f;
return (int)seconds;
} }
} }
} }

View File

@ -1,14 +0,0 @@
using System;
namespace YooAsset.Editor
{
[AttributeUsage(AttributeTargets.Class)]
public class TaskAttribute : Attribute
{
public string Desc;
public TaskAttribute(string desc)
{
Desc = desc;
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 35749e57d9a3da84aa60c348bc6bbe9d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,52 +0,0 @@
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Build.Pipeline;
using UnityEditor.Build.Pipeline.Interfaces;
namespace UnityEditor.Build.Pipeline.Tasks
{
public static class SBPBuildTasks
{
public static IList<IBuildTask> Create(string builtInShaderBundleName)
{
var buildTasks = new List<IBuildTask>();
// Setup
buildTasks.Add(new SwitchToBuildPlatform());
buildTasks.Add(new RebuildSpriteAtlasCache());
// Player Scripts
buildTasks.Add(new BuildPlayerScripts());
buildTasks.Add(new PostScriptsCallback());
// Dependency
buildTasks.Add(new CalculateSceneDependencyData());
#if UNITY_2019_3_OR_NEWER
buildTasks.Add(new CalculateCustomDependencyData());
#endif
buildTasks.Add(new CalculateAssetDependencyData());
buildTasks.Add(new StripUnusedSpriteSources());
buildTasks.Add(new CreateBuiltInShadersBundle(builtInShaderBundleName));
buildTasks.Add(new PostDependencyCallback());
// Packing
buildTasks.Add(new GenerateBundlePacking());
buildTasks.Add(new UpdateBundleObjectLayout());
buildTasks.Add(new GenerateBundleCommands());
buildTasks.Add(new GenerateSubAssetPathMaps());
buildTasks.Add(new GenerateBundleMaps());
buildTasks.Add(new PostPackingCallback());
// Writing
buildTasks.Add(new WriteSerializedFiles());
buildTasks.Add(new ArchiveAndCompressBundles());
buildTasks.Add(new AppendBundleHash());
buildTasks.Add(new GenerateLinkXml());
buildTasks.Add(new PostWritingCallback());
return buildTasks;
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: f38422f6a64300243af6b4fbf84644ba
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,5 +1,6 @@
using System; using System;
using System.Linq; using System.Linq;
using System.IO;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using UnityEditor; using UnityEditor;
@ -7,44 +8,187 @@ using UnityEngine;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
[TaskAttribute("资源构建内容打包")]
public class TaskBuilding : IBuildTask public class TaskBuilding : IBuildTask
{ {
public class BuildResultContext : IContextObject public class UnityManifestContext : IContextObject
{ {
public AssetBundleManifest UnityManifest; public AssetBundleManifest UnityManifest;
} }
void IBuildTask.Run(BuildContext context) void IBuildTask.Run(BuildContext context)
{ {
var buildParametersContext = context.GetContextObject<BuildParametersContext>(); var buildParametersContext = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>(); var buildMapContext = context.GetContextObject<BuildMapContext>();
// 模拟构建模式下跳过引擎构建 Debug.Log($"开始构建......");
var buildMode = buildParametersContext.Parameters.BuildMode; BuildAssetBundleOptions opt = buildParametersContext.GetPipelineBuildOptions();
if (buildMode == EBuildMode.SimulateBuild) AssetBundleManifest unityManifest = BuildPipeline.BuildAssetBundles(buildParametersContext.PipelineOutputDirectory, buildMapContext.GetPipelineBuilds(), opt, buildParametersContext.Parameters.BuildTarget);
return; if (unityManifest == null)
// 开始构建
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
BuildAssetBundleOptions buildOptions = buildParametersContext.GetPipelineBuildOptions();
AssetBundleManifest buildResults = BuildPipeline.BuildAssetBundles(pipelineOutputDirectory, buildMapContext.GetPipelineBuilds(), buildOptions, buildParametersContext.Parameters.BuildTarget);
if (buildResults == null)
{
throw new Exception("构建过程中发生错误!"); throw new Exception("构建过程中发生错误!");
}
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild) UnityManifestContext unityManifestContext = new UnityManifestContext();
unityManifestContext.UnityManifest = unityManifest;
context.SetContextObject(unityManifestContext);
// 拷贝原生文件
foreach (var bundleInfo in buildMapContext.BundleInfos)
{ {
string unityOutputManifestFilePath = $"{pipelineOutputDirectory}/{YooAssetSettings.OutputFolderName}"; if (bundleInfo.IsRawFile)
if (System.IO.File.Exists(unityOutputManifestFilePath) == false) {
throw new Exception("构建过程中发生严重错误!请查阅上下文日志!"); string dest = $"{buildParametersContext.PipelineOutputDirectory}/{bundleInfo.BundleName}";
foreach(var buildAsset in bundleInfo.BuildinAssets)
{
if(buildAsset.IsRawAsset)
EditorTools.CopyFile(buildAsset.AssetPath, dest, true);
}
}
} }
BuildLogger.Log("Unity引擎打包成功"); // 验证构建结果
BuildResultContext buildResultContext = new BuildResultContext(); if (buildParametersContext.Parameters.VerifyBuildingResult)
buildResultContext.UnityManifest = buildResults; {
context.SetContextObject(buildResultContext); VerifyingBuildingResult(context, unityManifest);
}
}
/// <summary>
/// 验证构建结果
/// </summary>
private void VerifyingBuildingResult(BuildContext context, AssetBundleManifest unityManifest)
{
var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
string[] buildedBundles = unityManifest.GetAllAssetBundles();
// 1. 过滤掉原生Bundle
List<BuildBundleInfo> expectBundles = new List<BuildBundleInfo>(buildedBundles.Length);
foreach(var bundleInfo in buildMapContext.BundleInfos)
{
if (bundleInfo.IsRawFile == false)
expectBundles.Add(bundleInfo);
}
// 2. 验证数量
if (buildedBundles.Length != expectBundles.Count)
{
Debug.LogWarning($"构建过程中可能存在无效的资源导致和预期构建的Bundle数量不一致");
}
// 3. 正向验证Bundle
foreach (var bundleName in buildedBundles)
{
if (buildMapContext.IsContainsBundle(bundleName) == false)
{
throw new Exception($"Should never get here !");
}
}
// 4. 反向验证Bundle
bool isPass = true;
foreach (var expectBundle in expectBundles)
{
bool isMatch = false;
foreach (var buildedBundle in buildedBundles)
{
if (buildedBundle == expectBundle.BundleName)
{
isMatch = true;
break;
}
}
if (isMatch == false)
{
isPass = false;
Debug.LogWarning($"没有找到预期构建的Bundle文件 : {expectBundle.BundleName}");
}
}
if(isPass == false)
{
throw new Exception("构建结果验证没有通过,请参考警告日志!");
}
// 5. 验证Asset
int progressValue = 0;
foreach (var buildedBundle in buildedBundles)
{
string filePath = $"{buildParameters.PipelineOutputDirectory}/{buildedBundle}";
string[] allBuildinAssetPaths = GetAssetBundleAllAssets(filePath);
string[] expectBuildinAssetPaths = buildMapContext.GetBuildinAssetPaths(buildedBundle);
if (expectBuildinAssetPaths.Length != allBuildinAssetPaths.Length)
{
Debug.LogWarning($"构建的Bundle文件内的资源对象数量和预期不匹配 : {buildedBundle}");
isPass = false;
continue;
}
foreach (var buildinAssetPath in allBuildinAssetPaths)
{
var guid = AssetDatabase.AssetPathToGUID(buildinAssetPath);
if (string.IsNullOrEmpty(guid))
{
Debug.LogWarning($"无效的资源路径,请检查路径是否带有特殊符号或中文:{buildinAssetPath}");
isPass = false;
continue;
}
bool isMatch = false;
foreach (var exceptBuildAssetPath in expectBuildinAssetPaths)
{
var guidExcept = AssetDatabase.AssetPathToGUID(exceptBuildAssetPath);
if (guid == guidExcept)
{
isMatch = true;
break;
}
}
if (isMatch == false)
{
Debug.LogWarning($"在构建的Bundle文件里发现了没有匹配的资源对象{buildinAssetPath}");
isPass = false;
continue;
}
}
EditorTools.DisplayProgressBar("验证构建结果", ++progressValue, buildedBundles.Length);
}
EditorTools.ClearProgressBar();
if (isPass == false)
{
throw new Exception("构建结果验证没有通过,请参考警告日志!");
}
// 卸载所有加载的Bundle
Debug.Log("构建结果验证成功!");
}
/// <summary>
/// 解析.manifest文件并获取资源列表
/// </summary>
private string[] GetAssetBundleAllAssets(string filePath)
{
string manifestFilePath = $"{filePath}.manifest";
List<string> assetLines = new List<string>();
using (StreamReader reader = File.OpenText(manifestFilePath))
{
string content;
bool findTarget = false;
while (null != (content = reader.ReadLine()))
{
if (content.StartsWith("Dependencies:"))
break;
if (findTarget == false && content.StartsWith("Assets:"))
findTarget = true;
if (findTarget)
{
if (content.StartsWith("- "))
{
string assetPath = content.TrimStart("- ".ToCharArray());
assetLines.Add(assetPath);
}
}
}
}
return assetLines.ToArray();
} }
} }
} }

View File

@ -1,58 +0,0 @@
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Build.Pipeline;
using UnityEditor.Build.Pipeline.Interfaces;
using UnityEditor.Build.Pipeline.Tasks;
namespace YooAsset.Editor
{
[TaskAttribute("资源构建内容打包")]
public class TaskBuilding_SBP : IBuildTask
{
public class BuildResultContext : IContextObject
{
public IBundleBuildResults Results;
}
void IBuildTask.Run(BuildContext context)
{
var buildParametersContext = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
// 模拟构建模式下跳过引擎构建
var buildMode = buildParametersContext.Parameters.BuildMode;
if (buildMode == EBuildMode.SimulateBuild)
return;
// 构建内容
var buildContent = new BundleBuildContent(buildMapContext.GetPipelineBuilds());
// 开始构建
IBundleBuildResults buildResults;
var buildParameters = buildParametersContext.GetSBPBuildParameters();
var taskList = SBPBuildTasks.Create(buildMapContext.ShadersBundleName);
ReturnCode exitCode = ContentPipeline.BuildAssetBundles(buildParameters, buildContent, out buildResults, taskList);
if (exitCode < 0)
{
throw new Exception($"构建过程中发生错误 : {exitCode}");
}
// 创建着色器信息
// 说明:解决因为着色器资源包导致验证失败。
// 例如:当项目里没有着色器,如果有依赖内置着色器就会验证失败。
string shadersBundleName = buildMapContext.ShadersBundleName;
if (buildResults.BundleInfos.ContainsKey(shadersBundleName))
{
buildMapContext.CreateShadersBundleInfo(shadersBundleName);
}
BuildLogger.Log("Unity引擎打包成功");
BuildResultContext buildResultContext = new BuildResultContext();
buildResultContext.Results = buildResults;
context.SetContextObject(buildResultContext);
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 1af5fed7e9f83174d868c12b41c4a79e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -6,95 +6,59 @@ using UnityEngine;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
[TaskAttribute("拷贝内置文件到流目录")] /// <summary>
/// 拷贝内置文件到StreamingAssets
/// </summary>
public class TaskCopyBuildinFiles : IBuildTask public class TaskCopyBuildinFiles : IBuildTask
{ {
void IBuildTask.Run(BuildContext context) void IBuildTask.Run(BuildContext context)
{ {
var buildParametersContext = context.GetContextObject<BuildParametersContext>(); // 注意:我们只有在强制重建的时候才会拷贝
var manifestContext = context.GetContextObject<ManifestContext>(); var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
var buildMode = buildParametersContext.Parameters.BuildMode; if(buildParameters.Parameters.ForceRebuild)
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
{ {
if (buildParametersContext.Parameters.CopyBuildinFileOption != ECopyBuildinFileOption.None) // 清空流目录
{ AssetBundleBuilderHelper.ClearStreamingAssetsFolder();
CopyBuildinFilesToStreaming(buildParametersContext, manifestContext);
} // 拷贝内置文件
var pipelineOutputDirectory = buildParameters.PipelineOutputDirectory;
CopyBuildinFilesToStreaming(pipelineOutputDirectory);
} }
} }
/// <summary> private void CopyBuildinFilesToStreaming(string pipelineOutputDirectory)
/// 拷贝首包资源文件
/// </summary>
private void CopyBuildinFilesToStreaming(BuildParametersContext buildParametersContext, ManifestContext manifestContext)
{ {
ECopyBuildinFileOption option = buildParametersContext.Parameters.CopyBuildinFileOption;
string packageOutputDirectory = buildParametersContext.GetPackageOutputDirectory();
string streamingAssetsDirectory = AssetBundleBuilderHelper.GetStreamingAssetsFolderPath();
string buildPackageName = buildParametersContext.Parameters.PackageName;
string buildPackageVersion = buildParametersContext.Parameters.PackageVersion;
// 加载补丁清单 // 加载补丁清单
PackageManifest manifest = manifestContext.Manifest; PatchManifest patchManifest = AssetBundleBuilderHelper.LoadPatchManifestFile(pipelineOutputDirectory);
// 清空流目录 // 拷贝文件列表
if (option == ECopyBuildinFileOption.ClearAndCopyAll || option == ECopyBuildinFileOption.ClearAndCopyByTags) foreach (var patchBundle in patchManifest.BundleList)
{ {
AssetBundleBuilderHelper.ClearStreamingAssetsFolder(); if (patchBundle.IsBuildin == false)
} continue;
// 拷贝补丁清单文件 string sourcePath = $"{pipelineOutputDirectory}/{patchBundle.BundleName}";
{ string destPath = $"{AssetBundleBuilderHelper.GetStreamingAssetsFolderPath()}/{patchBundle.Hash}";
string fileName = YooAssetSettingsData.GetManifestBinaryFileName(buildPackageName, buildPackageVersion); Debug.Log($"拷贝内置文件到流目录:{patchBundle.BundleName}");
string sourcePath = $"{packageOutputDirectory}/{fileName}";
string destPath = $"{streamingAssetsDirectory}/{fileName}";
EditorTools.CopyFile(sourcePath, destPath, true); EditorTools.CopyFile(sourcePath, destPath, true);
} }
// 拷贝补丁清单哈希文件 // 拷贝清单文件
{ {
string fileName = YooAssetSettingsData.GetPackageHashFileName(buildPackageName, buildPackageVersion); string sourcePath = $"{pipelineOutputDirectory}/{YooAssetSettingsData.Setting.PatchManifestFileName}";
string sourcePath = $"{packageOutputDirectory}/{fileName}"; string destPath = $"{AssetBundleBuilderHelper.GetStreamingAssetsFolderPath()}/{YooAssetSettingsData.Setting.PatchManifestFileName}";
string destPath = $"{streamingAssetsDirectory}/{fileName}";
EditorTools.CopyFile(sourcePath, destPath, true); EditorTools.CopyFile(sourcePath, destPath, true);
} }
// 拷贝补丁清单版本文件 // 拷贝清单哈希文件
{ {
string fileName = YooAssetSettingsData.GetPackageVersionFileName(buildPackageName); string sourcePath = $"{pipelineOutputDirectory}/{YooAssetSettingsData.Setting.PatchManifestHashFileName}";
string sourcePath = $"{packageOutputDirectory}/{fileName}"; string destPath = $"{AssetBundleBuilderHelper.GetStreamingAssetsFolderPath()}/{YooAssetSettingsData.Setting.PatchManifestHashFileName}";
string destPath = $"{streamingAssetsDirectory}/{fileName}";
EditorTools.CopyFile(sourcePath, destPath, true); EditorTools.CopyFile(sourcePath, destPath, true);
} }
// 拷贝文件列表(所有文件)
if (option == ECopyBuildinFileOption.ClearAndCopyAll || option == ECopyBuildinFileOption.OnlyCopyAll)
{
foreach (var packageBundle in manifest.BundleList)
{
string sourcePath = $"{packageOutputDirectory}/{packageBundle.FileName}";
string destPath = $"{streamingAssetsDirectory}/{packageBundle.FileName}";
EditorTools.CopyFile(sourcePath, destPath, true);
}
}
// 拷贝文件列表(带标签的文件)
if (option == ECopyBuildinFileOption.ClearAndCopyByTags || option == ECopyBuildinFileOption.OnlyCopyByTags)
{
string[] tags = buildParametersContext.Parameters.CopyBuildinFileTags.Split(';');
foreach (var packageBundle in manifest.BundleList)
{
if (packageBundle.HasTag(tags) == false)
continue;
string sourcePath = $"{packageOutputDirectory}/{packageBundle.FileName}";
string destPath = $"{streamingAssetsDirectory}/{packageBundle.FileName}";
EditorTools.CopyFile(sourcePath, destPath, true);
}
}
// 刷新目录 // 刷新目录
AssetDatabase.Refresh(); AssetDatabase.Refresh();
BuildLogger.Log($"内置文件拷贝完成:{streamingAssetsDirectory}");
} }
} }
} }

View File

@ -1,44 +0,0 @@
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset.Editor
{
[TaskAttribute("拷贝原生文件")]
public class TaskCopyRawFile : IBuildTask
{
void IBuildTask.Run(BuildContext context)
{
var buildParametersContext = context.GetContextObject<BuildParametersContext>();
var buildParameters = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
var buildMode = buildParameters.Parameters.BuildMode;
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
{
CopyRawBundle(buildMapContext, buildParametersContext);
}
}
/// <summary>
/// 拷贝原生文件
/// </summary>
private void CopyRawBundle(BuildMapContext buildMapContext, BuildParametersContext buildParametersContext)
{
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
foreach (var bundleInfo in buildMapContext.Collection)
{
if (bundleInfo.IsRawFile)
{
string dest = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}";
foreach (var assetInfo in bundleInfo.AllMainAssets)
{
if (assetInfo.IsRawAsset)
EditorTools.CopyFile(assetInfo.AssetPath, dest, true);
}
}
}
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 3625d4b8b5b79324ebf7ec19a87677e7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,384 +0,0 @@
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Build.Pipeline;
using UnityEditor.Build.Pipeline.Interfaces;
namespace YooAsset.Editor
{
public class ManifestContext : IContextObject
{
internal PackageManifest Manifest;
}
[TaskAttribute("创建清单文件")]
public class TaskCreateManifest : IBuildTask
{
void IBuildTask.Run(BuildContext context)
{
CreateManifestFile(context);
}
/// <summary>
/// 创建补丁清单文件到输出目录
/// </summary>
private void CreateManifestFile(BuildContext context)
{
var buildMapContext = context.GetContextObject<BuildMapContext>();
var buildParametersContext = context.GetContextObject<BuildParametersContext>();
var buildParameters = buildParametersContext.Parameters;
string packageOutputDirectory = buildParametersContext.GetPackageOutputDirectory();
// 创建新补丁清单
PackageManifest manifest = new PackageManifest();
manifest.FileVersion = YooAssetSettings.ManifestFileVersion;
manifest.EnableAddressable = buildMapContext.EnableAddressable;
manifest.OutputNameStyle = (int)buildParameters.OutputNameStyle;
manifest.PackageName = buildParameters.PackageName;
manifest.PackageVersion = buildParameters.PackageVersion;
manifest.BundleList = GetAllPackageBundle(context);
manifest.AssetList = GetAllPackageAsset(context, manifest);
// 更新Unity内置资源包的引用关系
if (buildParameters.BuildPipeline == EBuildPipeline.ScriptableBuildPipeline)
{
if (buildParameters.BuildMode == EBuildMode.IncrementalBuild)
{
var buildResultContext = context.GetContextObject<TaskBuilding_SBP.BuildResultContext>();
UpdateBuiltInBundleReference(manifest, buildResultContext, buildMapContext.ShadersBundleName);
}
}
// 更新资源包之间的引用关系
if (buildParameters.BuildPipeline == EBuildPipeline.ScriptableBuildPipeline)
{
if (buildParameters.BuildMode == EBuildMode.IncrementalBuild)
{
var buildResultContext = context.GetContextObject<TaskBuilding_SBP.BuildResultContext>();
UpdateScriptPipelineReference(manifest, buildResultContext);
}
}
// 更新资源包之间的引用关系
if (buildParameters.BuildPipeline == EBuildPipeline.BuiltinBuildPipeline)
{
if (buildParameters.BuildMode != EBuildMode.SimulateBuild)
{
var buildResultContext = context.GetContextObject<TaskBuilding.BuildResultContext>();
UpdateBuiltinPipelineReference(manifest, buildResultContext);
}
}
// 创建补丁清单文本文件
{
string fileName = YooAssetSettingsData.GetManifestJsonFileName(buildParameters.PackageName, buildParameters.PackageVersion);
string filePath = $"{packageOutputDirectory}/{fileName}";
ManifestTools.SerializeToJson(filePath, manifest);
BuildLogger.Log($"创建补丁清单文件:{filePath}");
}
// 创建补丁清单二进制文件
string packageHash;
{
string fileName = YooAssetSettingsData.GetManifestBinaryFileName(buildParameters.PackageName, buildParameters.PackageVersion);
string filePath = $"{packageOutputDirectory}/{fileName}";
ManifestTools.SerializeToBinary(filePath, manifest);
packageHash = HashUtility.FileMD5(filePath);
BuildLogger.Log($"创建补丁清单文件:{filePath}");
ManifestContext manifestContext = new ManifestContext();
byte[] bytesData = FileUtility.ReadAllBytes(filePath);
manifestContext.Manifest = ManifestTools.DeserializeFromBinary(bytesData);
context.SetContextObject(manifestContext);
}
// 创建补丁清单哈希文件
{
string fileName = YooAssetSettingsData.GetPackageHashFileName(buildParameters.PackageName, buildParameters.PackageVersion);
string filePath = $"{packageOutputDirectory}/{fileName}";
FileUtility.WriteAllText(filePath, packageHash);
BuildLogger.Log($"创建补丁清单哈希文件:{filePath}");
}
// 创建补丁清单版本文件
{
string fileName = YooAssetSettingsData.GetPackageVersionFileName(buildParameters.PackageName);
string filePath = $"{packageOutputDirectory}/{fileName}";
FileUtility.WriteAllText(filePath, buildParameters.PackageVersion);
BuildLogger.Log($"创建补丁清单版本文件:{filePath}");
}
}
/// <summary>
/// 获取资源包列表
/// </summary>
private List<PackageBundle> GetAllPackageBundle(BuildContext context)
{
var buildMapContext = context.GetContextObject<BuildMapContext>();
List<PackageBundle> result = new List<PackageBundle>(1000);
foreach (var bundleInfo in buildMapContext.Collection)
{
var packageBundle = bundleInfo.CreatePackageBundle();
result.Add(packageBundle);
}
return result;
}
/// <summary>
/// 获取资源列表
/// </summary>
private List<PackageAsset> GetAllPackageAsset(BuildContext context, PackageManifest manifest)
{
var buildMapContext = context.GetContextObject<BuildMapContext>();
List<PackageAsset> result = new List<PackageAsset>(1000);
foreach (var bundleInfo in buildMapContext.Collection)
{
var assetInfos = bundleInfo.GetAllMainAssetInfos();
foreach (var assetInfo in assetInfos)
{
PackageAsset packageAsset = new PackageAsset();
if (buildMapContext.EnableAddressable)
packageAsset.Address = assetInfo.Address;
else
packageAsset.Address = string.Empty;
packageAsset.AssetPath = assetInfo.AssetPath;
packageAsset.AssetTags = assetInfo.AssetTags.ToArray();
packageAsset.BundleID = GetAssetBundleID(assetInfo.BundleName, manifest);
packageAsset.DependIDs = GetAssetBundleDependIDs(packageAsset.BundleID, assetInfo, manifest);
result.Add(packageAsset);
}
}
return result;
}
private int[] GetAssetBundleDependIDs(int mainBundleID, BuildAssetInfo assetInfo, PackageManifest manifest)
{
List<int> result = new List<int>();
foreach (var dependAssetInfo in assetInfo.AllDependAssetInfos)
{
if (dependAssetInfo.HasBundleName())
{
int bundleID = GetAssetBundleID(dependAssetInfo.BundleName, manifest);
if (mainBundleID != bundleID)
{
if (result.Contains(bundleID) == false)
result.Add(bundleID);
}
}
}
return result.ToArray();
}
private int GetAssetBundleID(string bundleName, PackageManifest manifest)
{
for (int index = 0; index < manifest.BundleList.Count; index++)
{
if (manifest.BundleList[index].BundleName == bundleName)
return index;
}
throw new Exception($"Not found bundle name : {bundleName}");
}
/// <summary>
/// 更新Unity内置资源包的引用关系
/// </summary>
private void UpdateBuiltInBundleReference(PackageManifest manifest, TaskBuilding_SBP.BuildResultContext buildResultContext, string shadersBunldeName)
{
// 获取所有依赖着色器资源包的资源包列表
List<string> shaderBundleReferenceList = new List<string>();
foreach (var valuePair in buildResultContext.Results.BundleInfos)
{
if (valuePair.Value.Dependencies.Any(t => t == shadersBunldeName))
shaderBundleReferenceList.Add(valuePair.Key);
}
// 注意:没有任何资源依赖着色器
if (shaderBundleReferenceList.Count == 0)
return;
// 获取着色器资源包索引
Predicate<PackageBundle> predicate = new Predicate<PackageBundle>(s => s.BundleName == shadersBunldeName);
int shaderBundleId = manifest.BundleList.FindIndex(predicate);
if (shaderBundleId == -1)
throw new Exception("没有发现着色器资源包!");
// 检测依赖交集并更新依赖ID
HashSet<string> tagTemps = new HashSet<string>();
foreach (var packageAsset in manifest.AssetList)
{
List<string> dependBundles = GetPackageAssetAllDependBundles(manifest, packageAsset);
List<string> conflictAssetPathList = dependBundles.Intersect(shaderBundleReferenceList).ToList();
if (conflictAssetPathList.Count > 0)
{
List<int> newDependIDs = new List<int>(packageAsset.DependIDs);
if (newDependIDs.Contains(shaderBundleId) == false)
newDependIDs.Add(shaderBundleId);
packageAsset.DependIDs = newDependIDs.ToArray();
foreach (var tag in packageAsset.AssetTags)
{
if (tagTemps.Contains(tag) == false)
tagTemps.Add(tag);
}
}
}
// 更新资源包标签
var packageBundle = manifest.BundleList[shaderBundleId];
List<string> newTags = new List<string>(packageBundle.Tags);
foreach (var tag in tagTemps)
{
if (newTags.Contains(tag) == false)
newTags.Add(tag);
}
packageBundle.Tags = newTags.ToArray();
}
private List<string> GetPackageAssetAllDependBundles(PackageManifest manifest, PackageAsset packageAsset)
{
List<string> result = new List<string>();
string mainBundle = manifest.BundleList[packageAsset.BundleID].BundleName;
result.Add(mainBundle);
foreach (var dependID in packageAsset.DependIDs)
{
string dependBundle = manifest.BundleList[dependID].BundleName;
result.Add(dependBundle);
}
return result;
}
#region 资源包引用关系相关
private readonly Dictionary<string, int> _cachedBundleID = new Dictionary<string, int>(10000);
private readonly Dictionary<string, string[]> _cachedBundleDepends = new Dictionary<string, string[]>(10000);
private void UpdateScriptPipelineReference(PackageManifest manifest, TaskBuilding_SBP.BuildResultContext buildResultContext)
{
int progressValue;
int totalCount = manifest.BundleList.Count;
// 缓存资源包ID
_cachedBundleID.Clear();
progressValue = 0;
foreach (var packageBundle in manifest.BundleList)
{
int bundleID = GetAssetBundleID(packageBundle.BundleName, manifest);
_cachedBundleID.Add(packageBundle.BundleName, bundleID);
EditorTools.DisplayProgressBar("缓存资源包索引", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
// 缓存资源包依赖
_cachedBundleDepends.Clear();
progressValue = 0;
foreach (var packageBundle in manifest.BundleList)
{
if (packageBundle.IsRawFile)
{
_cachedBundleDepends.Add(packageBundle.BundleName, new string[] { });
continue;
}
if (buildResultContext.Results.BundleInfos.ContainsKey(packageBundle.BundleName) == false)
throw new Exception($"Not found bundle in SBP build results : {packageBundle.BundleName}");
var depends = buildResultContext.Results.BundleInfos[packageBundle.BundleName].Dependencies;
_cachedBundleDepends.Add(packageBundle.BundleName, depends);
EditorTools.DisplayProgressBar("缓存资源包依赖列表", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
// 计算资源包引用列表
foreach (var packageBundle in manifest.BundleList)
{
packageBundle.ReferenceIDs = GetBundleRefrenceIDs(manifest, packageBundle);
EditorTools.DisplayProgressBar("计算资源包引用关系", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
}
private void UpdateBuiltinPipelineReference(PackageManifest manifest, TaskBuilding.BuildResultContext buildResultContext)
{
int progressValue;
int totalCount = manifest.BundleList.Count;
// 缓存资源包ID
_cachedBundleID.Clear();
progressValue = 0;
foreach (var packageBundle in manifest.BundleList)
{
int bundleID = GetAssetBundleID(packageBundle.BundleName, manifest);
_cachedBundleID.Add(packageBundle.BundleName, bundleID);
EditorTools.DisplayProgressBar("缓存资源包索引", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
// 缓存资源包依赖
_cachedBundleDepends.Clear();
progressValue = 0;
foreach (var packageBundle in manifest.BundleList)
{
if (packageBundle.IsRawFile)
{
_cachedBundleDepends.Add(packageBundle.BundleName, new string[] { });
continue;
}
var depends = buildResultContext.UnityManifest.GetDirectDependencies(packageBundle.BundleName);
_cachedBundleDepends.Add(packageBundle.BundleName, depends);
EditorTools.DisplayProgressBar("缓存资源包依赖列表", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
// 计算资源包引用列表
progressValue = 0;
foreach (var packageBundle in manifest.BundleList)
{
packageBundle.ReferenceIDs = GetBundleRefrenceIDs(manifest, packageBundle);
EditorTools.DisplayProgressBar("计算资源包引用关系", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
}
private int[] GetBundleRefrenceIDs(PackageManifest manifest, PackageBundle targetBundle)
{
List<string> referenceList = new List<string>();
foreach (var packageBundle in manifest.BundleList)
{
string bundleName = packageBundle.BundleName;
if (bundleName == targetBundle.BundleName)
continue;
string[] dependencies = GetCachedBundleDepends(bundleName);
if (dependencies.Contains(targetBundle.BundleName))
{
referenceList.Add(bundleName);
}
}
List<int> result = new List<int>();
foreach (var bundleName in referenceList)
{
int bundleID = GetCachedBundleID(bundleName);
if (result.Contains(bundleID) == false)
result.Add(bundleID);
}
return result.ToArray();
}
private int GetCachedBundleID(string bundleName)
{
if (_cachedBundleID.TryGetValue(bundleName, out int value) == false)
{
throw new Exception($"Not found cached bundle ID : {bundleName}");
}
return value;
}
private string[] GetCachedBundleDepends(string bundleName)
{
if (_cachedBundleDepends.TryGetValue(bundleName, out string[] value) == false)
{
throw new Exception($"Not found cached bundle depends : {bundleName}");
}
return value;
}
#endregion
}
}

View File

@ -1,79 +0,0 @@
using System.Collections;
using System.Collections.Generic;
namespace YooAsset.Editor
{
[TaskAttribute("制作包裹")]
public class TaskCreatePackage : IBuildTask
{
void IBuildTask.Run(BuildContext context)
{
var buildParameters = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
var buildMode = buildParameters.Parameters.BuildMode;
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
{
CopyPackageFiles(buildParameters, buildMapContext);
}
}
/// <summary>
/// 拷贝补丁文件到补丁包目录
/// </summary>
private void CopyPackageFiles(BuildParametersContext buildParametersContext, BuildMapContext buildMapContext)
{
var buildParameters = buildParametersContext.Parameters;
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
string packageOutputDirectory = buildParametersContext.GetPackageOutputDirectory();
BuildLogger.Log($"开始拷贝补丁文件到补丁包目录:{packageOutputDirectory}");
if (buildParameters.BuildPipeline == EBuildPipeline.ScriptableBuildPipeline)
{
// 拷贝构建日志
{
string sourcePath = $"{pipelineOutputDirectory}/buildlogtep.json";
string destPath = $"{packageOutputDirectory}/buildlogtep.json";
EditorTools.CopyFile(sourcePath, destPath, true);
}
// 拷贝代码防裁剪配置
if (buildParameters.SBPParameters.WriteLinkXML)
{
string sourcePath = $"{pipelineOutputDirectory}/link.xml";
string destPath = $"{packageOutputDirectory}/link.xml";
EditorTools.CopyFile(sourcePath, destPath, true);
}
}
else if (buildParameters.BuildPipeline == EBuildPipeline.BuiltinBuildPipeline)
{
// 拷贝UnityManifest序列化文件
{
string sourcePath = $"{pipelineOutputDirectory}/{YooAssetSettings.OutputFolderName}";
string destPath = $"{packageOutputDirectory}/{YooAssetSettings.OutputFolderName}";
EditorTools.CopyFile(sourcePath, destPath, true);
}
// 拷贝UnityManifest文本文件
{
string sourcePath = $"{pipelineOutputDirectory}/{YooAssetSettings.OutputFolderName}.manifest";
string destPath = $"{packageOutputDirectory}/{YooAssetSettings.OutputFolderName}.manifest";
EditorTools.CopyFile(sourcePath, destPath, true);
}
}
else
{
throw new System.NotImplementedException();
}
// 拷贝所有补丁文件
int progressValue = 0;
int fileTotalCount = buildMapContext.Collection.Count;
foreach (var bundleInfo in buildMapContext.Collection)
{
EditorTools.CopyFile(bundleInfo.BundleInfo.BuildOutputFilePath, bundleInfo.BundleInfo.PackageOutputFilePath, true);
EditorTools.DisplayProgressBar("拷贝补丁文件", ++progressValue, fileTotalCount);
}
EditorTools.ClearProgressBar();
}
}
}

View File

@ -0,0 +1,154 @@
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset.Editor
{
/// <summary>
/// 创建补丁清单文件
/// </summary>
public class TaskCreatePatchManifest : IBuildTask
{
void IBuildTask.Run(BuildContext context)
{
var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
var encryptionContext = context.GetContextObject<TaskEncryption.EncryptionContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
CreatePatchManifestFile(buildParameters, buildMapContext, encryptionContext);
}
/// <summary>
/// 创建补丁清单文件到输出目录
/// </summary>
private void CreatePatchManifestFile(AssetBundleBuilder.BuildParametersContext buildParameters,
BuildMapContext buildMapContext, TaskEncryption.EncryptionContext encryptionContext)
{
// 创建新补丁清单
PatchManifest patchManifest = new PatchManifest();
patchManifest.ResourceVersion = buildParameters.Parameters.BuildVersion;
patchManifest.BuildinTags = buildParameters.Parameters.BuildinTags;
patchManifest.BundleList = GetAllPatchBundle(buildParameters, buildMapContext, encryptionContext);
patchManifest.AssetList = GetAllPatchAsset(buildMapContext, patchManifest);
// 创建补丁清单文件
string manifestFilePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettingsData.Setting.PatchManifestFileName}";
UnityEngine.Debug.Log($"创建补丁清单文件:{manifestFilePath}");
PatchManifest.Serialize(manifestFilePath, patchManifest);
// 创建补丁清单哈希文件
string manifestHashFilePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettingsData.Setting.PatchManifestHashFileName}";
string manifestHash = HashUtility.FileMD5(manifestFilePath);
UnityEngine.Debug.Log($"创建补丁清单哈希文件:{manifestHashFilePath}");
FileUtility.CreateFile(manifestHashFilePath, manifestHash);
}
/// <summary>
/// 获取资源包列表
/// </summary>
private List<PatchBundle> GetAllPatchBundle(AssetBundleBuilder.BuildParametersContext buildParameters,
BuildMapContext buildMapContext, TaskEncryption.EncryptionContext encryptionContext)
{
List<PatchBundle> result = new List<PatchBundle>(1000);
// 内置标记列表
List<string> buildinTags = buildParameters.Parameters.GetBuildinTags();
// 加载旧补丁清单
PatchManifest oldPatchManifest = null;
if (buildParameters.Parameters.ForceRebuild == false)
{
oldPatchManifest = AssetBundleBuilderHelper.LoadPatchManifestFile(buildParameters.PipelineOutputDirectory);
}
foreach (var bundleInfo in buildMapContext.BundleInfos)
{
var bundleName = bundleInfo.BundleName;
string filePath = $"{buildParameters.PipelineOutputDirectory}/{bundleName}";
string hash = HashUtility.FileMD5(filePath);
string crc = HashUtility.FileCRC32(filePath);
long size = FileUtility.GetFileSize(filePath);
int version = buildParameters.Parameters.BuildVersion;
string[] tags = buildMapContext.GetAssetTags(bundleName);
bool isEncrypted = encryptionContext.IsEncryptFile(bundleName);
bool isBuildin = IsBuildinBundle(tags, buildinTags);
bool isRawFile = bundleInfo.IsRawFile;
// 附加文件扩展名
if (buildParameters.Parameters.AppendFileExtension)
{
hash += bundleInfo.GetAppendExtension();
}
// 注意:如果文件没有变化使用旧版本号
if (oldPatchManifest != null && oldPatchManifest.Bundles.TryGetValue(bundleName, out PatchBundle value))
{
if (value.Hash == hash)
version = value.Version;
}
PatchBundle patchBundle = new PatchBundle(bundleName, hash, crc, size, version, tags);
patchBundle.SetFlagsValue(isEncrypted, isBuildin, isRawFile);
result.Add(patchBundle);
}
return result;
}
private bool IsBuildinBundle(string[] bundleTags, List<string> buildinTags)
{
// 注意没有任何标记的Bundle文件默认为内置文件
if (bundleTags.Length == 0)
return true;
foreach (var tag in bundleTags)
{
if (buildinTags.Contains(tag))
return true;
}
return false;
}
/// <summary>
/// 获取资源列表
/// </summary>
private List<PatchAsset> GetAllPatchAsset(BuildMapContext buildMapContext, PatchManifest patchManifest)
{
List<PatchAsset> result = new List<PatchAsset>(1000);
foreach (var bundleInfo in buildMapContext.BundleInfos)
{
var assetInfos = bundleInfo.GetAllPatchAssetInfos();
foreach (var assetInfo in assetInfos)
{
PatchAsset patchAsset = new PatchAsset();
patchAsset.AssetPath = assetInfo.AssetPath;
patchAsset.BundleID = GetAssetBundleID(assetInfo.BundleName, patchManifest);
patchAsset.DependIDs = GetAssetBundleDependIDs(assetInfo, patchManifest);
result.Add(patchAsset);
}
}
return result;
}
private int[] GetAssetBundleDependIDs(BuildAssetInfo assetInfo, PatchManifest patchManifest)
{
List<int> result = new List<int>();
foreach (var dependAssetInfo in assetInfo.AllDependAssetInfos)
{
if (dependAssetInfo.BundleNameIsValid() == false)
continue;
int bundleID = GetAssetBundleID(dependAssetInfo.BundleName, patchManifest);
if (result.Contains(bundleID) == false)
result.Add(bundleID);
}
return result.ToArray();
}
private int GetAssetBundleID(string bundleName, PatchManifest patchManifest)
{
for (int index = 0; index < patchManifest.BundleList.Count; index++)
{
if (patchManifest.BundleList[index].BundleName == bundleName)
return index;
}
throw new Exception($"Not found bundle name : {bundleName}");
}
}
}

View File

@ -0,0 +1,83 @@
using System.Collections;
using System.Collections.Generic;
namespace YooAsset.Editor
{
/// <summary>
/// 制作补丁包
/// </summary>
public class TaskCreatePatchPackage : IBuildTask
{
void IBuildTask.Run(BuildContext context)
{
var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
CopyPatchFiles(buildParameters);
}
/// <summary>
/// 拷贝补丁文件到补丁包目录
/// </summary>
private void CopyPatchFiles(AssetBundleBuilder.BuildParametersContext buildParameters)
{
string packageDirectory = buildParameters.GetPackageDirectory();
UnityEngine.Debug.Log($"开始拷贝补丁文件到补丁包目录:{packageDirectory}");
// 拷贝Report文件
{
string sourcePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettings.ReportFileName}";
string destPath = $"{packageDirectory}/{YooAssetSettings.ReportFileName}";
EditorTools.CopyFile(sourcePath, destPath, true);
UnityEngine.Debug.Log($"拷贝Report文件到{destPath}");
}
// 拷贝PatchManifest文件
{
string sourcePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettingsData.Setting.PatchManifestFileName}";
string destPath = $"{packageDirectory}/{YooAssetSettingsData.Setting.PatchManifestFileName}";
EditorTools.CopyFile(sourcePath, destPath, true);
UnityEngine.Debug.Log($"拷贝PatchManifest文件到{destPath}");
}
// 拷贝PatchManifest哈希文件
{
string sourcePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettingsData.Setting.PatchManifestHashFileName}";
string destPath = $"{packageDirectory}/{YooAssetSettingsData.Setting.PatchManifestHashFileName}";
EditorTools.CopyFile(sourcePath, destPath, true);
UnityEngine.Debug.Log($"拷贝PatchManifest哈希文件到{destPath}");
}
// 拷贝UnityManifest序列化文件
{
string sourcePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettingsData.Setting.UnityManifestFileName}";
string destPath = $"{packageDirectory}/{YooAssetSettingsData.Setting.UnityManifestFileName}";
EditorTools.CopyFile(sourcePath, destPath, true);
UnityEngine.Debug.Log($"拷贝UnityManifest文件到{destPath}");
}
// 拷贝UnityManifest文本文件
{
string sourcePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettingsData.Setting.UnityManifestFileName}.manifest";
string destPath = $"{packageDirectory}/{YooAssetSettingsData.Setting.UnityManifestFileName}.manifest";
EditorTools.CopyFile(sourcePath, destPath, true);
}
// 拷贝所有补丁文件
// 注意:拷贝的补丁文件都是需要玩家热更新的文件
int progressValue = 0;
PatchManifest patchManifest = AssetBundleBuilderHelper.LoadPatchManifestFile(buildParameters.PipelineOutputDirectory);
int patchFileTotalCount = patchManifest.BundleList.Count;
foreach (var patchBundle in patchManifest.BundleList)
{
if (patchBundle.Version == buildParameters.Parameters.BuildVersion)
{
string sourcePath = $"{buildParameters.PipelineOutputDirectory}/{patchBundle.BundleName}";
string destPath = $"{packageDirectory}/{patchBundle.Hash}";
EditorTools.CopyFile(sourcePath, destPath, true);
UnityEngine.Debug.Log($"拷贝补丁文件到补丁包:{patchBundle.BundleName}");
EditorTools.DisplayProgressBar("拷贝补丁文件", ++progressValue, patchFileTotalCount);
}
}
EditorTools.ClearProgressBar();
}
}
}

View File

@ -1,129 +1,108 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using UnityEditor;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
[TaskAttribute("创建构建报告文件")] /// <summary>
/// 创建报告文件
/// </summary>
public class TaskCreateReport : IBuildTask public class TaskCreateReport : IBuildTask
{ {
void IBuildTask.Run(BuildContext context) void IBuildTask.Run(BuildContext context)
{ {
var buildParameters = context.GetContextObject<BuildParametersContext>(); var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>(); var buildMapContext = context.GetContextObject<BuildMapContext>();
var manifestContext = context.GetContextObject<ManifestContext>(); CreateReportFile(buildParameters, buildMapContext);
var buildMode = buildParameters.Parameters.BuildMode;
if (buildMode != EBuildMode.SimulateBuild)
{
CreateReportFile(buildParameters, buildMapContext, manifestContext);
}
} }
private void CreateReportFile(BuildParametersContext buildParametersContext, BuildMapContext buildMapContext, ManifestContext manifestContext) private void CreateReportFile(AssetBundleBuilder.BuildParametersContext buildParameters, BuildMapContext buildMapContext)
{ {
var buildParameters = buildParametersContext.Parameters; PatchManifest patchManifest = AssetBundleBuilderHelper.LoadPatchManifestFile(buildParameters.PipelineOutputDirectory);
string packageOutputDirectory = buildParametersContext.GetPackageOutputDirectory();
PackageManifest manifest = manifestContext.Manifest;
BuildReport buildReport = new BuildReport(); BuildReport buildReport = new BuildReport();
buildParameters.StopWatch();
// 概述信息 // 概述信息
{ {
#if UNITY_2019_4_OR_NEWER
UnityEditor.PackageManager.PackageInfo packageInfo = UnityEditor.PackageManager.PackageInfo.FindForAssembly(typeof(BuildReport).Assembly);
if (packageInfo != null)
buildReport.Summary.YooVersion = packageInfo.version;
#endif
buildReport.Summary.UnityVersion = UnityEngine.Application.unityVersion; buildReport.Summary.UnityVersion = UnityEngine.Application.unityVersion;
buildReport.Summary.BuildDate = DateTime.Now.ToString(); buildReport.Summary.BuildTime = DateTime.Now.ToString();
buildReport.Summary.BuildSeconds = BuildRunner.TotalSeconds; buildReport.Summary.BuildSeconds = buildParameters.GetBuildingSeconds();
buildReport.Summary.BuildTarget = buildParameters.BuildTarget; buildReport.Summary.BuildTarget = buildParameters.Parameters.BuildTarget;
buildReport.Summary.BuildPipeline = buildParameters.BuildPipeline; buildReport.Summary.BuildVersion = buildParameters.Parameters.BuildVersion;
buildReport.Summary.BuildMode = buildParameters.BuildMode; buildReport.Summary.EnableAutoCollect = buildParameters.Parameters.EnableAutoCollect;
buildReport.Summary.BuildPackageName = buildParameters.PackageName; buildReport.Summary.AppendFileExtension = buildParameters.Parameters.AppendFileExtension;
buildReport.Summary.BuildPackageVersion = buildParameters.PackageVersion; buildReport.Summary.AutoCollectShaders = AssetBundleGrouperSettingData.Setting.AutoCollectShaders;
buildReport.Summary.EnableAddressable = buildMapContext.EnableAddressable; buildReport.Summary.ShadersBundleName = AssetBundleGrouperSettingData.Setting.ShadersBundleName;
buildReport.Summary.UniqueBundleName = buildMapContext.UniqueBundleName; buildReport.Summary.EncryptionServicesClassName = buildParameters.Parameters.EncryptionServices == null ?
buildReport.Summary.AutoAnalyzeRedundancy = buildParameters.AutoAnalyzeRedundancy; "null" : buildParameters.Parameters.EncryptionServices.GetType().FullName;
buildReport.Summary.ShareAssetPackRuleClassName = buildParameters.ShareAssetPackRule == null ?
"null" : buildParameters.ShareAssetPackRule.GetType().FullName;
buildReport.Summary.EncryptionServicesClassName = buildParameters.EncryptionServices == null ?
"null" : buildParameters.EncryptionServices.GetType().FullName;
// 构建参数 // 构建参数
buildReport.Summary.OutputNameStyle = buildParameters.OutputNameStyle; buildReport.Summary.ForceRebuild = buildParameters.Parameters.ForceRebuild;
buildReport.Summary.CompressOption = buildParameters.CompressOption; buildReport.Summary.BuildinTags = buildParameters.Parameters.BuildinTags;
buildReport.Summary.DisableWriteTypeTree = buildParameters.DisableWriteTypeTree; buildReport.Summary.CompressOption = buildParameters.Parameters.CompressOption;
buildReport.Summary.IgnoreTypeTreeChanges = buildParameters.IgnoreTypeTreeChanges; buildReport.Summary.AppendHash = buildParameters.Parameters.AppendHash;
buildReport.Summary.DisableWriteTypeTree = buildParameters.Parameters.DisableWriteTypeTree;
buildReport.Summary.IgnoreTypeTreeChanges = buildParameters.Parameters.IgnoreTypeTreeChanges;
buildReport.Summary.DisableLoadAssetByFileName = buildParameters.Parameters.DisableLoadAssetByFileName;
// 构建结果 // 构建结果
buildReport.Summary.AssetFileTotalCount = buildMapContext.AssetFileCount; buildReport.Summary.AssetFileTotalCount = buildMapContext.AssetFileCount;
buildReport.Summary.MainAssetTotalCount = GetMainAssetCount(manifest); buildReport.Summary.AllBundleTotalCount = GetAllBundleCount(patchManifest);
buildReport.Summary.AllBundleTotalCount = GetAllBundleCount(manifest); buildReport.Summary.AllBundleTotalSize = GetAllBundleSize(patchManifest);
buildReport.Summary.AllBundleTotalSize = GetAllBundleSize(manifest); buildReport.Summary.BuildinBundleTotalCount = GetBuildinBundleCount(patchManifest);
buildReport.Summary.EncryptedBundleTotalCount = GetEncryptedBundleCount(manifest); buildReport.Summary.BuildinBundleTotalSize = GetBuildinBundleSize(patchManifest);
buildReport.Summary.EncryptedBundleTotalSize = GetEncryptedBundleSize(manifest); buildReport.Summary.EncryptedBundleTotalCount = GetEncryptedBundleCount(patchManifest);
buildReport.Summary.RawBundleTotalCount = GetRawBundleCount(manifest); buildReport.Summary.EncryptedBundleTotalSize = GetEncryptedBundleSize(patchManifest);
buildReport.Summary.RawBundleTotalSize = GetRawBundleSize(manifest); buildReport.Summary.RawBundleTotalCount = GetRawBundleCount(patchManifest);
buildReport.Summary.RawBundleTotalSize = GetRawBundleSize(patchManifest);
} }
// 资源对象列表 // 资源对象列表
buildReport.AssetInfos = new List<ReportAssetInfo>(manifest.AssetList.Count); buildReport.AssetInfos = new List<ReportAssetInfo>(patchManifest.AssetList.Count);
foreach (var packageAsset in manifest.AssetList) foreach (var patchAsset in patchManifest.AssetList)
{ {
var mainBundle = manifest.BundleList[packageAsset.BundleID]; var mainBundle = patchManifest.BundleList[patchAsset.BundleID];
ReportAssetInfo reportAssetInfo = new ReportAssetInfo(); ReportAssetInfo reportAssetInfo = new ReportAssetInfo();
reportAssetInfo.Address = packageAsset.Address; reportAssetInfo.AssetPath = patchAsset.AssetPath;
reportAssetInfo.AssetPath = packageAsset.AssetPath; reportAssetInfo.MainBundle = mainBundle.BundleName;
reportAssetInfo.AssetTags = packageAsset.AssetTags; reportAssetInfo.DependBundles = GetDependBundles(patchManifest, patchAsset);
reportAssetInfo.AssetGUID = AssetDatabase.AssetPathToGUID(packageAsset.AssetPath); reportAssetInfo.DependAssets = GetDependAssets(buildMapContext, mainBundle.BundleName, patchAsset.AssetPath);
reportAssetInfo.MainBundleName = mainBundle.BundleName;
reportAssetInfo.MainBundleSize = mainBundle.FileSize;
reportAssetInfo.DependBundles = GetDependBundles(manifest, packageAsset);
reportAssetInfo.DependAssets = GetDependAssets(buildMapContext, mainBundle.BundleName, packageAsset.AssetPath);
buildReport.AssetInfos.Add(reportAssetInfo); buildReport.AssetInfos.Add(reportAssetInfo);
} }
// 资源包列表 // 资源包列表
buildReport.BundleInfos = new List<ReportBundleInfo>(manifest.BundleList.Count); buildReport.BundleInfos = new List<ReportBundleInfo>(patchManifest.BundleList.Count);
foreach (var packageBundle in manifest.BundleList) foreach (var patchBundle in patchManifest.BundleList)
{ {
ReportBundleInfo reportBundleInfo = new ReportBundleInfo(); ReportBundleInfo reportBundleInfo = new ReportBundleInfo();
reportBundleInfo.BundleName = packageBundle.BundleName; reportBundleInfo.BundleName = patchBundle.BundleName;
reportBundleInfo.FileName = packageBundle.FileName; reportBundleInfo.Hash = patchBundle.Hash;
reportBundleInfo.FileHash = packageBundle.FileHash; reportBundleInfo.CRC = patchBundle.CRC;
reportBundleInfo.FileCRC = packageBundle.FileCRC; reportBundleInfo.SizeBytes = patchBundle.SizeBytes;
reportBundleInfo.FileSize = packageBundle.FileSize; reportBundleInfo.Version = patchBundle.Version;
reportBundleInfo.IsRawFile = packageBundle.IsRawFile; reportBundleInfo.Tags = patchBundle.Tags;
reportBundleInfo.LoadMethod = (EBundleLoadMethod)packageBundle.LoadMethod; reportBundleInfo.Flags = patchBundle.Flags;
reportBundleInfo.Tags = packageBundle.Tags;
reportBundleInfo.ReferenceIDs = packageBundle.ReferenceIDs;
reportBundleInfo.AllBuiltinAssets = GetAllBuiltinAssets(buildMapContext, packageBundle.BundleName);
buildReport.BundleInfos.Add(reportBundleInfo); buildReport.BundleInfos.Add(reportBundleInfo);
} }
// 冗余资源列表 // 删除旧文件
buildReport.RedundancyInfos = new List<ReportRedundancyInfo>(buildMapContext.RedundancyInfos); string filePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettings.ReportFileName}";
if (File.Exists(filePath))
File.Delete(filePath);
// 序列化文件 // 序列化文件
string fileName = YooAssetSettingsData.GetReportFileName(buildParameters.PackageName, buildParameters.PackageVersion);
string filePath = $"{packageOutputDirectory}/{fileName}";
BuildReport.Serialize(filePath, buildReport); BuildReport.Serialize(filePath, buildReport);
BuildLogger.Log($"资源构建报告文件创建完成:{filePath}");
} }
/// <summary> /// <summary>
/// 获取资源对象依赖的所有资源包 /// 获取资源对象依赖的所有资源包
/// </summary> /// </summary>
private List<string> GetDependBundles(PackageManifest manifest, PackageAsset packageAsset) private List<string> GetDependBundles(PatchManifest patchManifest, PatchAsset patchAsset)
{ {
List<string> dependBundles = new List<string>(packageAsset.DependIDs.Length); List<string> dependBundles = new List<string>(patchAsset.DependIDs.Length);
foreach (int index in packageAsset.DependIDs) foreach (int index in patchAsset.DependIDs)
{ {
string dependBundleName = manifest.BundleList[index].BundleName; string dependBundleName = patchManifest.BundleList[index].BundleName;
dependBundles.Add(dependBundleName); dependBundles.Add(dependBundleName);
} }
return dependBundles; return dependBundles;
@ -135,14 +114,14 @@ namespace YooAsset.Editor
private List<string> GetDependAssets(BuildMapContext buildMapContext, string bundleName, string assetPath) private List<string> GetDependAssets(BuildMapContext buildMapContext, string bundleName, string assetPath)
{ {
List<string> result = new List<string>(); List<string> result = new List<string>();
var bundleInfo = buildMapContext.GetBundleInfo(bundleName); if (buildMapContext.TryGetBundleInfo(bundleName, out BuildBundleInfo bundleInfo))
{ {
BuildAssetInfo findAssetInfo = null; BuildAssetInfo findAssetInfo = null;
foreach (var assetInfo in bundleInfo.AllMainAssets) foreach (var buildinAsset in bundleInfo.BuildinAssets)
{ {
if (assetInfo.AssetPath == assetPath) if (buildinAsset.AssetPath == assetPath)
{ {
findAssetInfo = assetInfo; findAssetInfo = buildinAsset;
break; break;
} }
} }
@ -155,72 +134,83 @@ namespace YooAsset.Editor
result.Add(dependAssetInfo.AssetPath); result.Add(dependAssetInfo.AssetPath);
} }
} }
else
{
throw new Exception($"Not found bundle : {bundleName}");
}
return result; return result;
} }
/// <summary> private int GetAllBundleCount(PatchManifest patchManifest)
/// 获取该资源包内的所有资源(包括零依赖资源)
/// </summary>
private List<string> GetAllBuiltinAssets(BuildMapContext buildMapContext, string bundleName)
{ {
var bundleInfo = buildMapContext.GetBundleInfo(bundleName); return patchManifest.BundleList.Count;
return bundleInfo.GetAllBuiltinAssetPaths();
} }
private long GetAllBundleSize(PatchManifest patchManifest)
private int GetMainAssetCount(PackageManifest manifest)
{
return manifest.AssetList.Count;
}
private int GetAllBundleCount(PackageManifest manifest)
{
return manifest.BundleList.Count;
}
private long GetAllBundleSize(PackageManifest manifest)
{ {
long fileBytes = 0; long fileBytes = 0;
foreach (var packageBundle in manifest.BundleList) foreach (var patchBundle in patchManifest.BundleList)
{ {
fileBytes += packageBundle.FileSize; fileBytes += patchBundle.SizeBytes;
} }
return fileBytes; return fileBytes;
} }
private int GetEncryptedBundleCount(PackageManifest manifest) private int GetBuildinBundleCount(PatchManifest patchManifest)
{ {
int fileCount = 0; int fileCount = 0;
foreach (var packageBundle in manifest.BundleList) foreach (var patchBundle in patchManifest.BundleList)
{ {
if (packageBundle.LoadMethod != (byte)EBundleLoadMethod.Normal) if (patchBundle.IsBuildin)
fileCount++; fileCount++;
} }
return fileCount; return fileCount;
} }
private long GetEncryptedBundleSize(PackageManifest manifest) private long GetBuildinBundleSize(PatchManifest patchManifest)
{ {
long fileBytes = 0; long fileBytes = 0;
foreach (var packageBundle in manifest.BundleList) foreach (var patchBundle in patchManifest.BundleList)
{ {
if (packageBundle.LoadMethod != (byte)EBundleLoadMethod.Normal) if (patchBundle.IsBuildin)
fileBytes += packageBundle.FileSize; fileBytes += patchBundle.SizeBytes;
} }
return fileBytes; return fileBytes;
} }
private int GetRawBundleCount(PackageManifest manifest) private int GetEncryptedBundleCount(PatchManifest patchManifest)
{ {
int fileCount = 0; int fileCount = 0;
foreach (var packageBundle in manifest.BundleList) foreach (var patchBundle in patchManifest.BundleList)
{ {
if (packageBundle.IsRawFile) if (patchBundle.IsEncrypted)
fileCount++; fileCount++;
} }
return fileCount; return fileCount;
} }
private long GetRawBundleSize(PackageManifest manifest) private long GetEncryptedBundleSize(PatchManifest patchManifest)
{ {
long fileBytes = 0; long fileBytes = 0;
foreach (var packageBundle in manifest.BundleList) foreach (var patchBundle in patchManifest.BundleList)
{ {
if (packageBundle.IsRawFile) if (patchBundle.IsEncrypted)
fileBytes += packageBundle.FileSize; fileBytes += patchBundle.SizeBytes;
}
return fileBytes;
}
private int GetRawBundleCount(PatchManifest patchManifest)
{
int fileCount = 0;
foreach (var patchBundle in patchManifest.BundleList)
{
if (patchBundle.IsRawFile)
fileCount++;
}
return fileCount;
}
private long GetRawBundleSize(PatchManifest patchManifest)
{
long fileBytes = 0;
foreach (var patchBundle in patchManifest.BundleList)
{
if (patchBundle.IsRawFile)
fileBytes += patchBundle.SizeBytes;
} }
return fileBytes; return fileBytes;
} }

View File

@ -6,62 +6,76 @@ using System.Collections.Generic;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
[TaskAttribute("资源包加密")]
public class TaskEncryption : IBuildTask public class TaskEncryption : IBuildTask
{ {
public class EncryptionContext : IContextObject
{
public List<string> EncryptList;
/// <summary>
/// 检测是否为加密文件
/// </summary>
public bool IsEncryptFile(string bundleName)
{
return EncryptList.Contains(bundleName);
}
}
void IBuildTask.Run(BuildContext context) void IBuildTask.Run(BuildContext context)
{ {
var buildParameters = context.GetContextObject<BuildParametersContext>(); var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>(); var buildMapContext = context.GetContextObject<BuildMapContext>();
var buildMode = buildParameters.Parameters.BuildMode; EncryptionContext encryptionContext = new EncryptionContext();
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild) encryptionContext.EncryptList = EncryptFiles(buildParameters, buildMapContext);
{ context.SetContextObject(encryptionContext);
EncryptingBundleFiles(buildParameters, buildMapContext);
}
} }
/// <summary> /// <summary>
/// 加密文件 /// 加密文件
/// </summary> /// </summary>
private void EncryptingBundleFiles(BuildParametersContext buildParametersContext, BuildMapContext buildMapContext) private List<string> EncryptFiles(AssetBundleBuilder.BuildParametersContext buildParameters, BuildMapContext buildMapContext)
{ {
var encryptionServices = buildParametersContext.Parameters.EncryptionServices; var encryptionServices = buildParameters.Parameters.EncryptionServices;
// 加密资源列表
List<string> encryptList = new List<string>();
// 如果没有设置加密类
if (encryptionServices == null) if (encryptionServices == null)
return; return encryptList;
if (encryptionServices.GetType() == typeof(EncryptionNone))
return;
UnityEngine.Debug.Log($"开始加密资源文件");
int progressValue = 0; int progressValue = 0;
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory(); foreach (var bundleInfo in buildMapContext.BundleInfos)
foreach (var bundleInfo in buildMapContext.Collection)
{ {
EncryptFileInfo fileInfo = new EncryptFileInfo(); if (encryptionServices.Check(bundleInfo.BundleName))
fileInfo.BundleName = bundleInfo.BundleName;
fileInfo.FilePath = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}";
var encryptResult = encryptionServices.Encrypt(fileInfo);
if (encryptResult.LoadMethod != EBundleLoadMethod.Normal)
{ {
// 注意:原生文件不支持加密
if (bundleInfo.IsRawFile) if (bundleInfo.IsRawFile)
{ {
BuildLogger.Warning($"Encryption not support raw file : {bundleInfo.BundleName}"); UnityEngine.Debug.LogWarning($"Encryption not support raw file : {bundleInfo.BundleName}");
continue; continue;
} }
string filePath = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}.encrypt"; encryptList.Add(bundleInfo.BundleName);
FileUtility.WriteAllBytes(filePath, encryptResult.EncryptedData);
bundleInfo.EncryptedFilePath = filePath; // 注意:通过判断文件合法性,规避重复加密一个文件
bundleInfo.LoadMethod = encryptResult.LoadMethod; string filePath = $"{buildParameters.PipelineOutputDirectory}/{bundleInfo.BundleName}";
BuildLogger.Log($"Bundle文件加密完成{filePath}"); byte[] fileData = File.ReadAllBytes(filePath);
if (EditorTools.CheckBundleFileValid(fileData))
{
byte[] bytes = encryptionServices.Encrypt(fileData);
File.WriteAllBytes(filePath, bytes);
UnityEngine.Debug.Log($"文件加密完成:{filePath}");
}
} }
// 进度条 // 进度条
EditorTools.DisplayProgressBar("加密资源包", ++progressValue, buildMapContext.Collection.Count); EditorTools.DisplayProgressBar("加密资源包", ++progressValue, buildMapContext.BundleInfos.Count);
} }
EditorTools.ClearProgressBar(); EditorTools.ClearProgressBar();
return encryptList;
} }
} }
} }

View File

@ -7,219 +7,35 @@ using UnityEditor;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
[TaskAttribute("获取资源构建内容")]
public class TaskGetBuildMap : IBuildTask public class TaskGetBuildMap : IBuildTask
{ {
void IBuildTask.Run(BuildContext context) void IBuildTask.Run(BuildContext context)
{ {
var buildParametersContext = context.GetContextObject<BuildParametersContext>(); var buildMapContext = BuildMapHelper.SetupBuildMap();
var buildMapContext = CreateBuildMap(buildParametersContext.Parameters);
context.SetContextObject(buildMapContext); context.SetContextObject(buildMapContext);
BuildLogger.Log("构建内容准备完毕!");
// 检测构建结果 // 检测构建结果
CheckBuildMapContent(buildMapContext); CheckBuildMapContent(buildMapContext);
} }
/// <summary>
/// 资源构建上下文
/// </summary>
public BuildMapContext CreateBuildMap(BuildParameters buildParameters)
{
EBuildMode buildMode = buildParameters.BuildMode;
string packageName = buildParameters.PackageName;
IShareAssetPackRule sharePackRule = buildParameters.ShareAssetPackRule;
bool autoAnalyzeRedundancy = buildParameters.AutoAnalyzeRedundancy;
Dictionary<string, BuildAssetInfo> allBuildAssetInfoDic = new Dictionary<string, BuildAssetInfo>(1000);
// 1. 检测配置合法性
AssetBundleCollectorSettingData.Setting.CheckConfigError();
// 2. 获取所有收集器收集的资源
var collectResult = AssetBundleCollectorSettingData.Setting.GetPackageAssets(buildMode, packageName);
List<CollectAssetInfo> allCollectAssetInfos = collectResult.CollectAssets;
// 3. 剔除未被引用的依赖项资源
RemoveZeroReferenceAssets(allCollectAssetInfos);
// 4. 录入所有收集器收集的资源
foreach (var collectAssetInfo in allCollectAssetInfos)
{
if (allBuildAssetInfoDic.ContainsKey(collectAssetInfo.AssetPath) == false)
{
var buildAssetInfo = new BuildAssetInfo(collectAssetInfo.CollectorType, collectAssetInfo.BundleName,
collectAssetInfo.Address, collectAssetInfo.AssetPath, collectAssetInfo.IsRawAsset);
buildAssetInfo.AddAssetTags(collectAssetInfo.AssetTags);
buildAssetInfo.AddBundleTags(collectAssetInfo.AssetTags);
allBuildAssetInfoDic.Add(collectAssetInfo.AssetPath, buildAssetInfo);
}
else
{
throw new Exception($"Should never get here !");
}
}
// 5. 录入所有收集资源的依赖资源
foreach (var collectAssetInfo in allCollectAssetInfos)
{
string collectAssetBundleName = collectAssetInfo.BundleName;
foreach (var dependAssetPath in collectAssetInfo.DependAssets)
{
if (allBuildAssetInfoDic.ContainsKey(dependAssetPath))
{
allBuildAssetInfoDic[dependAssetPath].AddBundleTags(collectAssetInfo.AssetTags);
allBuildAssetInfoDic[dependAssetPath].AddReferenceBundleName(collectAssetBundleName);
}
else
{
var buildAssetInfo = new BuildAssetInfo(dependAssetPath);
buildAssetInfo.AddBundleTags(collectAssetInfo.AssetTags);
buildAssetInfo.AddReferenceBundleName(collectAssetBundleName);
allBuildAssetInfoDic.Add(dependAssetPath, buildAssetInfo);
}
}
}
// 6. 填充所有收集资源的依赖列表
foreach (var collectAssetInfo in allCollectAssetInfos)
{
var dependAssetInfos = new List<BuildAssetInfo>(collectAssetInfo.DependAssets.Count);
foreach (var dependAssetPath in collectAssetInfo.DependAssets)
{
if (allBuildAssetInfoDic.TryGetValue(dependAssetPath, out BuildAssetInfo value))
dependAssetInfos.Add(value);
else
throw new Exception("Should never get here !");
}
allBuildAssetInfoDic[collectAssetInfo.AssetPath].SetAllDependAssetInfos(dependAssetInfos);
}
// 7. 记录关键信息
BuildMapContext context = new BuildMapContext();
context.AssetFileCount = allBuildAssetInfoDic.Count;
context.EnableAddressable = collectResult.Command.EnableAddressable;
context.UniqueBundleName = collectResult.Command.UniqueBundleName;
context.ShadersBundleName = collectResult.Command.ShadersBundleName;
// 8. 计算共享的资源包名
if (autoAnalyzeRedundancy)
{
var command = collectResult.Command;
foreach (var buildAssetInfo in allBuildAssetInfoDic.Values)
{
buildAssetInfo.CalculateShareBundleName(sharePackRule, command.UniqueBundleName, command.PackageName, command.ShadersBundleName);
}
}
else
{
// 记录冗余资源
foreach (var buildAssetInfo in allBuildAssetInfoDic.Values)
{
if (buildAssetInfo.IsRedundancyAsset())
{
var redundancyInfo = new ReportRedundancyInfo();
redundancyInfo.AssetPath = buildAssetInfo.AssetPath;
redundancyInfo.AssetType = AssetDatabase.GetMainAssetTypeAtPath(buildAssetInfo.AssetPath).Name;
redundancyInfo.AssetGUID = AssetDatabase.AssetPathToGUID(buildAssetInfo.AssetPath);
redundancyInfo.FileSize = FileUtility.GetFileSize(buildAssetInfo.AssetPath);
redundancyInfo.Number = buildAssetInfo.GetReferenceBundleCount();
context.RedundancyInfos.Add(redundancyInfo);
}
}
}
// 9. 移除不参与构建的资源
List<BuildAssetInfo> removeBuildList = new List<BuildAssetInfo>();
foreach (var buildAssetInfo in allBuildAssetInfoDic.Values)
{
if (buildAssetInfo.HasBundleName() == false)
removeBuildList.Add(buildAssetInfo);
}
foreach (var removeValue in removeBuildList)
{
allBuildAssetInfoDic.Remove(removeValue.AssetPath);
}
// 10. 构建资源包
var allPackAssets = allBuildAssetInfoDic.Values.ToList();
if (allPackAssets.Count == 0)
throw new Exception("构建的资源列表不能为空");
foreach (var assetInfo in allPackAssets)
{
context.PackAsset(assetInfo);
}
return context;
}
private void RemoveZeroReferenceAssets(List<CollectAssetInfo> allCollectAssetInfos)
{
// 1. 检测是否任何存在依赖资源
bool hasAnyDependAsset = false;
foreach (var collectAssetInfo in allCollectAssetInfos)
{
var collectorType = collectAssetInfo.CollectorType;
if (collectorType == ECollectorType.DependAssetCollector)
{
hasAnyDependAsset = true;
break;
}
}
if (hasAnyDependAsset == false)
return;
// 2. 获取所有主资源的依赖资源集合
HashSet<string> allDependAsset = new HashSet<string>();
foreach (var collectAssetInfo in allCollectAssetInfos)
{
var collectorType = collectAssetInfo.CollectorType;
if (collectorType == ECollectorType.MainAssetCollector || collectorType == ECollectorType.StaticAssetCollector)
{
foreach (var dependAsset in collectAssetInfo.DependAssets)
{
if (allDependAsset.Contains(dependAsset) == false)
allDependAsset.Add(dependAsset);
}
}
}
// 3. 找出所有零引用的依赖资源集合
List<CollectAssetInfo> removeList = new List<CollectAssetInfo>();
foreach (var collectAssetInfo in allCollectAssetInfos)
{
var collectorType = collectAssetInfo.CollectorType;
if (collectorType == ECollectorType.DependAssetCollector)
{
if (allDependAsset.Contains(collectAssetInfo.AssetPath) == false)
removeList.Add(collectAssetInfo);
}
}
// 4. 移除所有零引用的依赖资源
foreach (var removeValue in removeList)
{
BuildLogger.Log($"发现未被依赖的资源并自动移除 : {removeValue.AssetPath}");
allCollectAssetInfos.Remove(removeValue);
}
}
/// <summary> /// <summary>
/// 检测构建结果 /// 检测构建结果
/// </summary> /// </summary>
private void CheckBuildMapContent(BuildMapContext buildMapContext) private void CheckBuildMapContent(BuildMapContext buildMapContext)
{ {
foreach (var bundleInfo in buildMapContext.Collection) foreach (var bundleInfo in buildMapContext.BundleInfos)
{ {
// 注意:原生文件资源包只能包含一个原生文件 // 注意:原生文件资源包只能包含一个原生文件
bool isRawFile = bundleInfo.IsRawFile; bool isRawFile = bundleInfo.IsRawFile;
if (isRawFile) if (isRawFile)
{ {
if (bundleInfo.AllMainAssets.Count != 1) if (bundleInfo.BuildinAssets.Count != 1)
throw new Exception($"The bundle does not support multiple raw asset : {bundleInfo.BundleName}"); throw new Exception("The bundle does not support multiple raw asset : {bundleInfo.BundleName}");
continue; continue;
} }
// 注意:原生文件不能被其它资源文件依赖 // 注意:原生文件不能被其它资源文件依赖
foreach (var assetInfo in bundleInfo.AllMainAssets) foreach (var assetInfo in bundleInfo.BuildinAssets)
{ {
if (assetInfo.AllDependAssetInfos != null) if (assetInfo.AllDependAssetInfos != null)
{ {

View File

@ -6,85 +6,63 @@ using UnityEditor;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
[TaskAttribute("资源构建准备工作")]
public class TaskPrepare : IBuildTask public class TaskPrepare : IBuildTask
{ {
void IBuildTask.Run(BuildContext context) void IBuildTask.Run(BuildContext context)
{ {
var buildParametersContext = context.GetContextObject<BuildParametersContext>(); var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
var buildParameters = buildParametersContext.Parameters; buildParameters.BeginWatch();
// 检测构建参数合法性 // 检测构建平台是否合法
if (buildParameters.BuildTarget == BuildTarget.NoTarget) if (buildParameters.Parameters.BuildTarget == BuildTarget.NoTarget)
throw new Exception("请选择目标平台"); throw new Exception("请选择目标平台");
if (string.IsNullOrEmpty(buildParameters.PackageName))
throw new Exception("包裹名称不能为空");
if (string.IsNullOrEmpty(buildParameters.PackageVersion))
throw new Exception("包裹版本不能为空");
if (buildParameters.BuildMode != EBuildMode.SimulateBuild) // 检测构建版本是否合法
if (buildParameters.Parameters.BuildVersion <= 0)
throw new Exception("请先设置版本号");
// 检测输出目录是否为空
if (string.IsNullOrEmpty(buildParameters.PipelineOutputDirectory))
throw new Exception("输出目录不能为空");
// 增量更新时候的必要检测
if (buildParameters.Parameters.ForceRebuild == false)
{ {
#if UNITY_2021_3_OR_NEWER // 检测历史版本是否存在
if (buildParameters.BuildPipeline == EBuildPipeline.BuiltinBuildPipeline) if (AssetBundleBuilderHelper.HasAnyPackageVersion(buildParameters.Parameters.BuildTarget, buildParameters.Parameters.OutputRoot) == false)
{ throw new Exception("没有发现任何历史版本,请尝试强制重建");
BuildLogger.Warning("推荐使用可编程构建管线SBP");
}
#endif
// 检测当前是否正在构建资源包 // 检测构建版本是否合法
if (BuildPipeline.isBuildingPlayer) int maxPackageVersion = AssetBundleBuilderHelper.GetMaxPackageVersion(buildParameters.Parameters.BuildTarget, buildParameters.Parameters.OutputRoot);
throw new Exception("当前正在构建资源包,请结束后再试"); if (buildParameters.Parameters.BuildVersion <= maxPackageVersion)
throw new Exception("构建版本不能小于历史版本");
// 检测是否有未保存场景 // 检测补丁包是否已经存在
if (EditorTools.HasDirtyScenes()) string packageDirectory = buildParameters.GetPackageDirectory();
throw new Exception("检测到未保存的场景文件"); if (Directory.Exists(packageDirectory))
throw new Exception($"补丁包已经存在:{packageDirectory}");
// 检测首包资源标签 // 检测内置资源分类标签是否一致
if (buildParameters.CopyBuildinFileOption == ECopyBuildinFileOption.ClearAndCopyByTags PatchManifest oldPatchManifest = AssetBundleBuilderHelper.LoadPatchManifestFile(buildParameters.PipelineOutputDirectory);
|| buildParameters.CopyBuildinFileOption == ECopyBuildinFileOption.OnlyCopyByTags) if (buildParameters.Parameters.BuildinTags != oldPatchManifest.BuildinTags)
{ throw new Exception($"增量更新时内置资源标签必须一致:{buildParameters.Parameters.BuildinTags} != {oldPatchManifest.BuildinTags}");
if (string.IsNullOrEmpty(buildParameters.CopyBuildinFileTags))
throw new Exception("首包资源标签不能为空!");
}
// 检测共享资源打包规则
if (buildParameters.ShareAssetPackRule == null)
throw new Exception("共享资源打包规则不能为空!");
#if UNITY_WEBGL
if (buildParameters.EncryptionServices != null)
{
if (buildParameters.EncryptionServices.GetType() != typeof(EncryptionNone))
{
throw new Exception("WebGL平台不支持加密");
}
}
#endif
// 检测包裹输出目录是否存在
string packageOutputDirectory = buildParametersContext.GetPackageOutputDirectory();
if (Directory.Exists(packageOutputDirectory))
throw new Exception($"本次构建的补丁目录已经存在:{packageOutputDirectory}");
// 保存改动的资源
AssetDatabase.SaveAssets();
} }
if (buildParameters.BuildMode == EBuildMode.ForceRebuild) // 如果是强制重建
if (buildParameters.Parameters.ForceRebuild)
{ {
// 删除总目录 // 删除平台总目录
string platformDirectory = $"{buildParameters.OutputRoot}/{buildParameters.BuildTarget}/{buildParameters.PackageName}"; string platformDirectory = $"{buildParameters.Parameters.OutputRoot}/{buildParameters.Parameters.BuildTarget}";
if (EditorTools.DeleteDirectory(platformDirectory)) if (EditorTools.DeleteDirectory(platformDirectory))
{ {
BuildLogger.Log($"删除平台总目录:{platformDirectory}"); UnityEngine.Debug.Log($"删除平台总目录:{platformDirectory}");
} }
} }
// 如果输出目录不存在 // 如果输出目录不存在
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory(); if (EditorTools.CreateDirectory(buildParameters.PipelineOutputDirectory))
if (EditorTools.CreateDirectory(pipelineOutputDirectory))
{ {
BuildLogger.Log($"创建输出目录:{pipelineOutputDirectory}"); UnityEngine.Debug.Log($"创建输出目录:{buildParameters.PipelineOutputDirectory}");
} }
} }
} }

View File

@ -1,119 +0,0 @@
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
namespace YooAsset.Editor
{
[TaskAttribute("更新资源包信息")]
public class TaskUpdateBundleInfo : IBuildTask
{
void IBuildTask.Run(BuildContext context)
{
var buildParametersContext = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
string packageOutputDirectory = buildParametersContext.GetPackageOutputDirectory();
int outputNameStyle = (int)buildParametersContext.Parameters.OutputNameStyle;
// 1.检测文件名长度
foreach (var bundleInfo in buildMapContext.Collection)
{
// NOTE检测文件名长度不要超过260字符。
string fileName = bundleInfo.BundleName;
if (fileName.Length >= 260)
throw new Exception($"The output bundle name is too long {fileName.Length} chars : {fileName}");
}
// 2.更新构建输出的文件路径
foreach (var bundleInfo in buildMapContext.Collection)
{
if (bundleInfo.IsEncryptedFile)
bundleInfo.BundleInfo.BuildOutputFilePath = bundleInfo.EncryptedFilePath;
else
bundleInfo.BundleInfo.BuildOutputFilePath = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}";
}
// 3.更新文件其它信息
foreach (var bundleInfo in buildMapContext.Collection)
{
string buildOutputFilePath = bundleInfo.BundleInfo.BuildOutputFilePath;
bundleInfo.BundleInfo.ContentHash = GetBundleContentHash(bundleInfo, context);
bundleInfo.BundleInfo.FileHash = GetBundleFileHash(buildOutputFilePath, buildParametersContext);
bundleInfo.BundleInfo.FileCRC = GetBundleFileCRC(buildOutputFilePath, buildParametersContext);
bundleInfo.BundleInfo.FileSize = GetBundleFileSize(buildOutputFilePath, buildParametersContext);
}
// 4.更新补丁包输出的文件路径
foreach (var bundleInfo in buildMapContext.Collection)
{
string fileExtension = ManifestTools.GetRemoteBundleFileExtension(bundleInfo.BundleName);
string fileName = ManifestTools.GetRemoteBundleFileName(outputNameStyle, bundleInfo.BundleName, fileExtension, bundleInfo.BundleInfo.FileHash);
bundleInfo.BundleInfo.PackageOutputFilePath = $"{packageOutputDirectory}/{fileName}";
}
}
private string GetBundleContentHash(BuildBundleInfo bundleInfo, BuildContext context)
{
var buildParametersContext = context.GetContextObject<BuildParametersContext>();
var parameters = buildParametersContext.Parameters;
var buildMode = parameters.BuildMode;
if (buildMode == EBuildMode.DryRunBuild || buildMode == EBuildMode.SimulateBuild)
return "00000000000000000000000000000000"; //32位
if (bundleInfo.IsRawFile)
{
string filePath = bundleInfo.BundleInfo.BuildOutputFilePath;
return HashUtility.FileMD5(filePath);
}
if (parameters.BuildPipeline == EBuildPipeline.BuiltinBuildPipeline)
{
var buildResult = context.GetContextObject<TaskBuilding.BuildResultContext>();
var hash = buildResult.UnityManifest.GetAssetBundleHash(bundleInfo.BundleName);
if (hash.isValid)
return hash.ToString();
else
throw new Exception($"Not found bundle in build result : {bundleInfo.BundleName}");
}
else if (parameters.BuildPipeline == EBuildPipeline.ScriptableBuildPipeline)
{
// 注意当资源包的依赖列表发生变化的时候ContentHash也会发生变化
var buildResult = context.GetContextObject<TaskBuilding_SBP.BuildResultContext>();
if (buildResult.Results.BundleInfos.TryGetValue(bundleInfo.BundleName, out var value))
return value.Hash.ToString();
else
throw new Exception($"Not found bundle in build result : {bundleInfo.BundleName}");
}
else
{
throw new System.NotImplementedException();
}
}
private string GetBundleFileHash(string filePath, BuildParametersContext buildParametersContext)
{
var buildMode = buildParametersContext.Parameters.BuildMode;
if (buildMode == EBuildMode.DryRunBuild || buildMode == EBuildMode.SimulateBuild)
return "00000000000000000000000000000000"; //32位
else
return HashUtility.FileMD5(filePath);
}
private string GetBundleFileCRC(string filePath, BuildParametersContext buildParametersContext)
{
var buildMode = buildParametersContext.Parameters.BuildMode;
if (buildMode == EBuildMode.DryRunBuild || buildMode == EBuildMode.SimulateBuild)
return "00000000"; //8位
else
return HashUtility.FileCRC32(filePath);
}
private long GetBundleFileSize(string filePath, BuildParametersContext buildParametersContext)
{
var buildMode = buildParametersContext.Parameters.BuildMode;
if (buildMode == EBuildMode.DryRunBuild || buildMode == EBuildMode.SimulateBuild)
return 0;
else
return FileUtility.GetFileSize(filePath);
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 4882f54fbf0bcb04680fb581deae4889
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,137 +0,0 @@
using System;
using System.Linq;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace YooAsset.Editor
{
[TaskAttribute("验证构建结果")]
public class TaskVerifyBuildResult : IBuildTask
{
void IBuildTask.Run(BuildContext context)
{
var buildParametersContext = context.GetContextObject<BuildParametersContext>();
// 模拟构建模式下跳过验证
if (buildParametersContext.Parameters.BuildMode == EBuildMode.SimulateBuild)
return;
// 验证构建结果
if (buildParametersContext.Parameters.VerifyBuildingResult)
{
var buildResultContext = context.GetContextObject<TaskBuilding.BuildResultContext>();
VerifyingBuildingResult(context, buildResultContext.UnityManifest);
}
}
/// <summary>
/// 验证构建结果
/// </summary>
private void VerifyingBuildingResult(BuildContext context, AssetBundleManifest unityManifest)
{
var buildParametersContext = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
string[] unityCreateBundles = unityManifest.GetAllAssetBundles();
// 1. 过滤掉原生Bundle
string[] mapBundles = buildMapContext.Collection.Where(t => t.IsRawFile == false).Select(t => t.BundleName).ToArray();
// 2. 验证Bundle
List<string> exceptBundleList1 = unityCreateBundles.Except(mapBundles).ToList();
if (exceptBundleList1.Count > 0)
{
foreach (var exceptBundle in exceptBundleList1)
{
BuildLogger.Warning($"差异资源包: {exceptBundle}");
}
throw new System.Exception("存在差异资源包!请查看警告信息!");
}
// 3. 验证Bundle
List<string> exceptBundleList2 = mapBundles.Except(unityCreateBundles).ToList();
if (exceptBundleList2.Count > 0)
{
foreach (var exceptBundle in exceptBundleList2)
{
BuildLogger.Warning($"差异资源包: {exceptBundle}");
}
throw new System.Exception("存在差异资源包!请查看警告信息!");
}
// 4. 验证Asset
/*
bool isPass = true;
var buildMode = buildParametersContext.Parameters.BuildMode;
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
{
int progressValue = 0;
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
foreach (var buildedBundle in buildedBundles)
{
string filePath = $"{pipelineOutputDirectory}/{buildedBundle}";
string[] buildedAssetPaths = GetAssetBundleAllAssets(filePath);
string[] mapAssetPaths = buildMapContext.GetBuildinAssetPaths(buildedBundle);
if (mapAssetPaths.Length != buildedAssetPaths.Length)
{
BuildLogger.Warning($"构建的Bundle文件内的资源对象数量和预期不匹配 : {buildedBundle}");
var exceptAssetList1 = mapAssetPaths.Except(buildedAssetPaths).ToList();
foreach (var excpetAsset in exceptAssetList1)
{
BuildLogger.Warning($"构建失败的资源对象路径为 : {excpetAsset}");
}
var exceptAssetList2 = buildedAssetPaths.Except(mapAssetPaths).ToList();
foreach (var excpetAsset in exceptAssetList2)
{
BuildLogger.Warning($"构建失败的资源对象路径为 : {excpetAsset}");
}
isPass = false;
continue;
}
EditorTools.DisplayProgressBar("验证构建结果", ++progressValue, buildedBundles.Length);
}
EditorTools.ClearProgressBar();
if (isPass == false)
{
throw new Exception("构建结果验证没有通过,请参考警告日志!");
}
}
*/
BuildLogger.Log("构建结果验证成功!");
}
/// <summary>
/// 解析.manifest文件并获取资源列表
/// </summary>
private string[] GetAssetBundleAllAssets(string filePath)
{
string manifestFilePath = $"{filePath}.manifest";
List<string> assetLines = new List<string>();
using (StreamReader reader = File.OpenText(manifestFilePath))
{
string content;
bool findTarget = false;
while (null != (content = reader.ReadLine()))
{
if (content.StartsWith("Dependencies:"))
break;
if (findTarget == false && content.StartsWith("Assets:"))
findTarget = true;
if (findTarget)
{
if (content.StartsWith("- "))
{
string assetPath = content.TrimStart("- ".ToCharArray());
assetLines.Add(assetPath);
}
}
}
}
return assetLines.ToArray();
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: b883ac0c3c25e8143847a9326e2961cf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,68 +0,0 @@
using System;
using System.Linq;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEditor.Build.Pipeline.Interfaces;
namespace YooAsset.Editor
{
[TaskAttribute("验证构建结果")]
public class TaskVerifyBuildResult_SBP : IBuildTask
{
void IBuildTask.Run(BuildContext context)
{
var buildParametersContext = context.GetContextObject<BuildParametersContext>();
// 模拟构建模式下跳过验证
if (buildParametersContext.Parameters.BuildMode == EBuildMode.SimulateBuild)
return;
// 验证构建结果
if (buildParametersContext.Parameters.VerifyBuildingResult)
{
var buildResultContext = context.GetContextObject<TaskBuilding_SBP.BuildResultContext>();
VerifyingBuildingResult(context, buildResultContext.Results);
}
}
/// <summary>
/// 验证构建结果
/// </summary>
private void VerifyingBuildingResult(BuildContext context, IBundleBuildResults buildResults)
{
var buildParameters = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
List<string> unityCreateBundles = buildResults.BundleInfos.Keys.ToList();
// 1. 过滤掉原生Bundle
List<string> expectBundles = buildMapContext.Collection.Where(t => t.IsRawFile == false).Select(t => t.BundleName).ToList();
// 2. 验证Bundle
List<string> exceptBundleList1 = unityCreateBundles.Except(expectBundles).ToList();
if (exceptBundleList1.Count > 0)
{
foreach (var exceptBundle in exceptBundleList1)
{
BuildLogger.Warning($"差异资源包: {exceptBundle}");
}
throw new System.Exception("存在差异资源包!请查看警告信息!");
}
// 3. 验证Bundle
List<string> exceptBundleList2 = expectBundles.Except(unityCreateBundles).ToList();
if (exceptBundleList2.Count > 0)
{
foreach (var exceptBundle in exceptBundleList2)
{
BuildLogger.Warning($"差异资源包: {exceptBundle}");
}
throw new System.Exception("存在差异资源包!请查看警告信息!");
}
BuildLogger.Log("构建结果验证成功!");
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 16aa7c2c37209a043b4f33d7854047c6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,11 +0,0 @@

namespace YooAsset.Editor
{
public class EncryptionNone : IEncryptionServices
{
public EncryptResult Encrypt(EncryptFileInfo fileInfo)
{
throw new System.NotImplementedException();
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 46b8b200b841799498896403d9d427c2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,29 +0,0 @@

namespace YooAsset.Editor
{
/// <summary>
/// 资源包流水线的构建模式
/// </summary>
public enum EBuildMode
{
/// <summary>
/// 强制重建模式
/// </summary>
ForceRebuild,
/// <summary>
/// 增量构建模式
/// </summary>
IncrementalBuild,
/// <summary>
/// 演练构建模式
/// </summary>
DryRunBuild,
/// <summary>
/// 模拟构建模式
/// </summary>
SimulateBuild,
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 0b6f2523a865e454d8fa3f48a2852d5a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,19 +0,0 @@

namespace YooAsset.Editor
{
/// <summary>
/// 构建管线类型
/// </summary>
public enum EBuildPipeline
{
/// <summary>
/// 传统内置构建管线
/// </summary>
BuiltinBuildPipeline,
/// <summary>
/// 可编程构建管线
/// </summary>
ScriptableBuildPipeline,
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: e53e56a0f6b01dd4c933249d2bda8d78
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,34 +0,0 @@

namespace YooAsset.Editor
{
/// <summary>
/// 首包资源文件的拷贝方式
/// </summary>
public enum ECopyBuildinFileOption
{
/// <summary>
/// 不拷贝任何文件
/// </summary>
None = 0,
/// <summary>
/// 先清空已有文件,然后拷贝所有文件
/// </summary>
ClearAndCopyAll,
/// <summary>
/// 先清空已有文件,然后按照资源标签拷贝文件
/// </summary>
ClearAndCopyByTags,
/// <summary>
/// 不清空已有文件,直接拷贝所有文件
/// </summary>
OnlyCopyAll,
/// <summary>
/// 不清空已有文件,直接按照资源标签拷贝文件
/// </summary>
OnlyCopyByTags,
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 4defd475b635cdf4b87108140d3a0ad1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,19 +0,0 @@

namespace YooAsset.Editor
{
/// <summary>
/// 输出文件名称的样式
/// </summary>
public enum EOutputNameStyle
{
/// <summary>
/// 哈希值名称
/// </summary>
HashName = 1,
/// <summary>
/// 资源包名称 + 哈希值名称
/// </summary>
BundleName_HashName = 4,
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 84c5eff5dedf53343897e83f6b10eea6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,18 @@

namespace YooAsset.Editor
{
public interface IEncryptionServices
{
/// <summary>
/// 检测是否需要加密
/// </summary>
bool Check(string bundleName);
/// <summary>
/// 加密方法
/// </summary>
/// <param name="fileData">要加密的文件数据</param>
/// <returns>返回加密后的字节数据</returns>
byte[] Encrypt(byte[] fileData);
}
}

View File

@ -1,349 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace YooAsset.Editor
{
[Serializable]
public class AssetBundleCollector
{
/// <summary>
/// 收集路径
/// 注意:支持文件夹或单个资源文件
/// </summary>
public string CollectPath = string.Empty;
/// <summary>
/// 收集器的GUID
/// </summary>
public string CollectorGUID = string.Empty;
/// <summary>
/// 收集器类型
/// </summary>
public ECollectorType CollectorType = ECollectorType.MainAssetCollector;
/// <summary>
/// 寻址规则类名
/// </summary>
public string AddressRuleName = nameof(AddressByFileName);
/// <summary>
/// 打包规则类名
/// </summary>
public string PackRuleName = nameof(PackDirectory);
/// <summary>
/// 过滤规则类名
/// </summary>
public string FilterRuleName = nameof(CollectAll);
/// <summary>
/// 资源分类标签
/// </summary>
public string AssetTags = string.Empty;
/// <summary>
/// 用户自定义数据
/// </summary>
public string UserData = string.Empty;
/// <summary>
/// 收集器是否有效
/// </summary>
public bool IsValid()
{
if (AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(CollectPath) == null)
return false;
if (CollectorType == ECollectorType.None)
return false;
if (AssetBundleCollectorSettingData.HasAddressRuleName(AddressRuleName) == false)
return false;
if (AssetBundleCollectorSettingData.HasPackRuleName(PackRuleName) == false)
return false;
if (AssetBundleCollectorSettingData.HasFilterRuleName(FilterRuleName) == false)
return false;
return true;
}
/// <summary>
/// 检测配置错误
/// </summary>
public void CheckConfigError()
{
string assetGUID = AssetDatabase.AssetPathToGUID(CollectPath);
if (string.IsNullOrEmpty(assetGUID))
throw new Exception($"Invalid collect path : {CollectPath}");
if (CollectorType == ECollectorType.None)
throw new Exception($"{nameof(ECollectorType)}.{ECollectorType.None} is invalid in collector : {CollectPath}");
if (AssetBundleCollectorSettingData.HasPackRuleName(PackRuleName) == false)
throw new Exception($"Invalid {nameof(IPackRule)} class type : {PackRuleName} in collector : {CollectPath}");
if (AssetBundleCollectorSettingData.HasFilterRuleName(FilterRuleName) == false)
throw new Exception($"Invalid {nameof(IFilterRule)} class type : {FilterRuleName} in collector : {CollectPath}");
if (AssetBundleCollectorSettingData.HasAddressRuleName(AddressRuleName) == false)
throw new Exception($"Invalid {nameof(IAddressRule)} class type : {AddressRuleName} in collector : {CollectPath}");
}
/// <summary>
/// 修复配置错误
/// </summary>
public bool FixConfigError()
{
bool isFixed = false;
if (string.IsNullOrEmpty(CollectorGUID) == false)
{
string convertAssetPath = AssetDatabase.GUIDToAssetPath(CollectorGUID);
if (string.IsNullOrEmpty(convertAssetPath))
{
Debug.LogWarning($"Collector GUID {CollectorGUID} is invalid and has been auto removed !");
CollectorGUID = string.Empty;
isFixed = true;
}
else
{
if (CollectPath != convertAssetPath)
{
CollectPath = convertAssetPath;
isFixed = true;
Debug.LogWarning($"Fix collect path : {CollectPath} -> {convertAssetPath}");
}
}
}
/*
string convertGUID = AssetDatabase.AssetPathToGUID(CollectPath);
if(string.IsNullOrEmpty(convertGUID) == false)
{
CollectorGUID = convertGUID;
}
*/
return isFixed;
}
/// <summary>
/// 获取打包收集的资源文件
/// </summary>
public List<CollectAssetInfo> GetAllCollectAssets(CollectCommand command, AssetBundleCollectorGroup group)
{
// 注意:模拟构建模式下只收集主资源
if (command.BuildMode == EBuildMode.SimulateBuild)
{
if (CollectorType != ECollectorType.MainAssetCollector)
return new List<CollectAssetInfo>();
}
Dictionary<string, CollectAssetInfo> result = new Dictionary<string, CollectAssetInfo>(1000);
// 检测是否为原生资源打包规则
IPackRule packRuleInstance = AssetBundleCollectorSettingData.GetPackRuleInstance(PackRuleName);
bool isRawFilePackRule = packRuleInstance.IsRawFilePackRule();
// 检测原生资源包的收集器类型
if (isRawFilePackRule && CollectorType != ECollectorType.MainAssetCollector)
throw new Exception($"The raw file pack rule must be set to {nameof(ECollectorType)}.{ECollectorType.MainAssetCollector} : {CollectPath}");
if (string.IsNullOrEmpty(CollectPath))
throw new Exception($"The collect path is null or empty in group : {group.GroupName}");
// 收集打包资源
if (AssetDatabase.IsValidFolder(CollectPath))
{
string collectDirectory = CollectPath;
string[] findAssets = EditorTools.FindAssets(EAssetSearchType.All, collectDirectory);
foreach (string assetPath in findAssets)
{
if (IsValidateAsset(assetPath, isRawFilePackRule) && IsCollectAsset(assetPath))
{
if (result.ContainsKey(assetPath) == false)
{
var collectAssetInfo = CreateCollectAssetInfo(command, group, assetPath, isRawFilePackRule);
result.Add(assetPath, collectAssetInfo);
}
else
{
throw new Exception($"The collecting asset file is existed : {assetPath} in collector : {CollectPath}");
}
}
}
}
else
{
string assetPath = CollectPath;
if (IsValidateAsset(assetPath, isRawFilePackRule) && IsCollectAsset(assetPath))
{
var collectAssetInfo = CreateCollectAssetInfo(command, group, assetPath, isRawFilePackRule);
result.Add(assetPath, collectAssetInfo);
}
else
{
throw new Exception($"The collecting single asset file is invalid : {assetPath} in collector : {CollectPath}");
}
}
// 检测可寻址地址是否重复
if (command.EnableAddressable)
{
var addressTemper = new Dictionary<string, string>();
foreach (var collectInfoPair in result)
{
if (collectInfoPair.Value.CollectorType == ECollectorType.MainAssetCollector)
{
string address = collectInfoPair.Value.Address;
string assetPath = collectInfoPair.Value.AssetPath;
if (addressTemper.TryGetValue(address, out var existed) == false)
addressTemper.Add(address, assetPath);
else
throw new Exception($"The address is existed : {address} in collector : {CollectPath} \nAssetPath:\n {existed}\n {assetPath}");
}
}
}
// 返回列表
return result.Values.ToList();
}
private CollectAssetInfo CreateCollectAssetInfo(CollectCommand command, AssetBundleCollectorGroup group, string assetPath, bool isRawFilePackRule)
{
string address = GetAddress(command, group, assetPath);
string bundleName = GetBundleName(command, group, assetPath);
List<string> assetTags = GetAssetTags(group);
CollectAssetInfo collectAssetInfo = new CollectAssetInfo(CollectorType, bundleName, address, assetPath, isRawFilePackRule, assetTags);
// 注意:模拟构建模式下不需要收集依赖资源
if (command.BuildMode == EBuildMode.SimulateBuild)
collectAssetInfo.DependAssets = new List<string>();
else
collectAssetInfo.DependAssets = GetAllDependencies(assetPath);
return collectAssetInfo;
}
private bool IsValidateAsset(string assetPath, bool isRawFilePackRule)
{
if (assetPath.StartsWith("Assets/") == false && assetPath.StartsWith("Packages/") == false)
{
UnityEngine.Debug.LogError($"Invalid asset path : {assetPath}");
return false;
}
// 忽略文件夹
if (AssetDatabase.IsValidFolder(assetPath))
return false;
// 忽略编辑器下的类型资源
Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
if (assetType == typeof(LightingDataAsset))
return false;
// 检测原生文件是否合规
if (isRawFilePackRule)
{
string extension = EditorTools.RemoveFirstChar(System.IO.Path.GetExtension(assetPath));
if (extension == EAssetFileExtension.unity.ToString() || extension == EAssetFileExtension.prefab.ToString() ||
extension == EAssetFileExtension.fbx.ToString() || extension == EAssetFileExtension.mat.ToString() ||
extension == EAssetFileExtension.controller.ToString() || extension == EAssetFileExtension.anim.ToString() ||
extension == EAssetFileExtension.ttf.ToString() || extension == EAssetFileExtension.shader.ToString())
{
UnityEngine.Debug.LogWarning($"Raw file pack rule can not support file estension : {extension}");
return false;
}
// 注意:原生文件只支持无依赖关系的资源
/*
string[] depends = AssetDatabase.GetDependencies(assetPath, true);
if (depends.Length != 1)
{
UnityEngine.Debug.LogWarning($"Raw file pack rule can not support estension : {extension}");
return false;
}
*/
}
else
{
// 忽略Unity无法识别的无效文件
// 注意:只对非原生文件收集器处理
if (assetType == typeof(UnityEditor.DefaultAsset))
{
UnityEngine.Debug.LogWarning($"Cannot pack default asset : {assetPath}");
return false;
}
}
string fileExtension = System.IO.Path.GetExtension(assetPath);
if (DefaultFilterRule.IsIgnoreFile(fileExtension))
return false;
return true;
}
private bool IsCollectAsset(string assetPath)
{
// 根据规则设置过滤资源文件
IFilterRule filterRuleInstance = AssetBundleCollectorSettingData.GetFilterRuleInstance(FilterRuleName);
return filterRuleInstance.IsCollectAsset(new FilterRuleData(assetPath));
}
private string GetAddress(CollectCommand command, AssetBundleCollectorGroup group, string assetPath)
{
if (command.EnableAddressable == false)
return string.Empty;
if (CollectorType != ECollectorType.MainAssetCollector)
return string.Empty;
IAddressRule addressRuleInstance = AssetBundleCollectorSettingData.GetAddressRuleInstance(AddressRuleName);
string adressValue = addressRuleInstance.GetAssetAddress(new AddressRuleData(assetPath, CollectPath, group.GroupName, UserData));
return adressValue;
}
private string GetBundleName(CollectCommand command, AssetBundleCollectorGroup group, string assetPath)
{
System.Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
if (assetType == typeof(UnityEngine.Shader) || assetType == typeof(UnityEngine.ShaderVariantCollection))
{
// 获取着色器打包规则结果
PackRuleResult packRuleResult = DefaultPackRule.CreateShadersPackRuleResult();
return packRuleResult.GetMainBundleName(command.PackageName, command.UniqueBundleName);
}
else
{
// 获取其它资源打包规则结果
IPackRule packRuleInstance = AssetBundleCollectorSettingData.GetPackRuleInstance(PackRuleName);
PackRuleResult packRuleResult = packRuleInstance.GetPackRuleResult(new PackRuleData(assetPath, CollectPath, group.GroupName, UserData));
return packRuleResult.GetMainBundleName(command.PackageName, command.UniqueBundleName);
}
}
private List<string> GetAssetTags(AssetBundleCollectorGroup group)
{
List<string> tags = EditorTools.StringToStringList(group.AssetTags, ';');
List<string> temper = EditorTools.StringToStringList(AssetTags, ';');
tags.AddRange(temper);
return tags;
}
private List<string> GetAllDependencies(string mainAssetPath)
{
string[] depends = AssetDatabase.GetDependencies(mainAssetPath, true);
List<string> result = new List<string>(depends.Length);
foreach (string assetPath in depends)
{
if (IsValidateAsset(assetPath, false))
{
// 注意:排除主资源对象
if (assetPath != mainAssetPath)
result.Add(assetPath);
}
}
return result;
}
}
}

View File

@ -1,381 +0,0 @@
using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace YooAsset.Editor
{
public class AssetBundleCollectorConfig
{
public const string ConfigVersion = "2.4";
public const string XmlVersion = "Version";
public const string XmlCommon = "Common";
public const string XmlEnableAddressable = "AutoAddressable";
public const string XmlUniqueBundleName = "UniqueBundleName";
public const string XmlShowPackageView = "ShowPackageView";
public const string XmlShowEditorAlias = "ShowEditorAlias";
public const string XmlPackage = "Package";
public const string XmlPackageName = "PackageName";
public const string XmlPackageDesc = "PackageDesc";
public const string XmlGroup = "Group";
public const string XmlGroupActiveRule = "GroupActiveRule";
public const string XmlGroupName = "GroupName";
public const string XmlGroupDesc = "GroupDesc";
public const string XmlCollector = "Collector";
public const string XmlCollectPath = "CollectPath";
public const string XmlCollectorGUID = "CollectGUID";
public const string XmlCollectorType = "CollectType";
public const string XmlAddressRule = "AddressRule";
public const string XmlPackRule = "PackRule";
public const string XmlFilterRule = "FilterRule";
public const string XmlUserData = "UserData";
public const string XmlAssetTags = "AssetTags";
/// <summary>
/// 导入XML配置表
/// </summary>
public static void ImportXmlConfig(string filePath)
{
if (File.Exists(filePath) == false)
throw new FileNotFoundException(filePath);
if (Path.GetExtension(filePath) != ".xml")
throw new Exception($"Only support xml : {filePath}");
// 加载配置文件
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
XmlElement root = xmlDoc.DocumentElement;
// 读取配置版本
string configVersion = root.GetAttribute(XmlVersion);
if (configVersion != ConfigVersion)
{
if (UpdateXmlConfig(xmlDoc) == false)
throw new Exception($"The config version update failed : {configVersion} -> {ConfigVersion}");
else
Debug.Log($"The config version update succeed : {configVersion} -> {ConfigVersion}");
}
// 读取公共配置
bool enableAddressable = false;
bool uniqueBundleName = false;
bool showPackageView = false;
bool showEditorAlias = false;
var commonNodeList = root.GetElementsByTagName(XmlCommon);
if (commonNodeList.Count > 0)
{
XmlElement commonElement = commonNodeList[0] as XmlElement;
if (commonElement.HasAttribute(XmlEnableAddressable) == false)
throw new Exception($"Not found attribute {XmlEnableAddressable} in {XmlCommon}");
if (commonElement.HasAttribute(XmlUniqueBundleName) == false)
throw new Exception($"Not found attribute {XmlUniqueBundleName} in {XmlCommon}");
if (commonElement.HasAttribute(XmlShowPackageView) == false)
throw new Exception($"Not found attribute {XmlShowPackageView} in {XmlCommon}");
if (commonElement.HasAttribute(XmlShowEditorAlias) == false)
throw new Exception($"Not found attribute {XmlShowEditorAlias} in {XmlCommon}");
enableAddressable = commonElement.GetAttribute(XmlEnableAddressable) == "True" ? true : false;
uniqueBundleName = commonElement.GetAttribute(XmlUniqueBundleName) == "True" ? true : false;
showPackageView = commonElement.GetAttribute(XmlShowPackageView) == "True" ? true : false;
showEditorAlias = commonElement.GetAttribute(XmlShowEditorAlias) == "True" ? true : false;
}
// 读取包裹配置
List<AssetBundleCollectorPackage> packages = new List<AssetBundleCollectorPackage>();
var packageNodeList = root.GetElementsByTagName(XmlPackage);
foreach (var packageNode in packageNodeList)
{
XmlElement packageElement = packageNode as XmlElement;
if (packageElement.HasAttribute(XmlPackageName) == false)
throw new Exception($"Not found attribute {XmlPackageName} in {XmlPackage}");
if (packageElement.HasAttribute(XmlPackageDesc) == false)
throw new Exception($"Not found attribute {XmlPackageDesc} in {XmlPackage}");
AssetBundleCollectorPackage package = new AssetBundleCollectorPackage();
package.PackageName = packageElement.GetAttribute(XmlPackageName);
package.PackageDesc = packageElement.GetAttribute(XmlPackageDesc);
packages.Add(package);
// 读取分组配置
var groupNodeList = packageElement.GetElementsByTagName(XmlGroup);
foreach (var groupNode in groupNodeList)
{
XmlElement groupElement = groupNode as XmlElement;
if (groupElement.HasAttribute(XmlGroupActiveRule) == false)
throw new Exception($"Not found attribute {XmlGroupActiveRule} in {XmlGroup}");
if (groupElement.HasAttribute(XmlGroupName) == false)
throw new Exception($"Not found attribute {XmlGroupName} in {XmlGroup}");
if (groupElement.HasAttribute(XmlGroupDesc) == false)
throw new Exception($"Not found attribute {XmlGroupDesc} in {XmlGroup}");
if (groupElement.HasAttribute(XmlAssetTags) == false)
throw new Exception($"Not found attribute {XmlAssetTags} in {XmlGroup}");
AssetBundleCollectorGroup group = new AssetBundleCollectorGroup();
group.ActiveRuleName = groupElement.GetAttribute(XmlGroupActiveRule);
group.GroupName = groupElement.GetAttribute(XmlGroupName);
group.GroupDesc = groupElement.GetAttribute(XmlGroupDesc);
group.AssetTags = groupElement.GetAttribute(XmlAssetTags);
package.Groups.Add(group);
// 读取收集器配置
var collectorNodeList = groupElement.GetElementsByTagName(XmlCollector);
foreach (var collectorNode in collectorNodeList)
{
XmlElement collectorElement = collectorNode as XmlElement;
if (collectorElement.HasAttribute(XmlCollectPath) == false)
throw new Exception($"Not found attribute {XmlCollectPath} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlCollectorGUID) == false)
throw new Exception($"Not found attribute {XmlCollectorGUID} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlCollectorType) == false)
throw new Exception($"Not found attribute {XmlCollectorType} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlAddressRule) == false)
throw new Exception($"Not found attribute {XmlAddressRule} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlPackRule) == false)
throw new Exception($"Not found attribute {XmlPackRule} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlFilterRule) == false)
throw new Exception($"Not found attribute {XmlFilterRule} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlUserData) == false)
throw new Exception($"Not found attribute {XmlUserData} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlAssetTags) == false)
throw new Exception($"Not found attribute {XmlAssetTags} in {XmlCollector}");
AssetBundleCollector collector = new AssetBundleCollector();
collector.CollectPath = collectorElement.GetAttribute(XmlCollectPath);
collector.CollectorGUID = collectorElement.GetAttribute(XmlCollectorGUID);
collector.CollectorType = EditorTools.NameToEnum<ECollectorType>(collectorElement.GetAttribute(XmlCollectorType));
collector.AddressRuleName = collectorElement.GetAttribute(XmlAddressRule);
collector.PackRuleName = collectorElement.GetAttribute(XmlPackRule);
collector.FilterRuleName = collectorElement.GetAttribute(XmlFilterRule);
collector.UserData = collectorElement.GetAttribute(XmlUserData);
collector.AssetTags = collectorElement.GetAttribute(XmlAssetTags);
group.Collectors.Add(collector);
}
}
}
// 检测配置错误
foreach(var package in packages)
{
package.CheckConfigError();
}
// 保存配置数据
AssetBundleCollectorSettingData.ClearAll();
AssetBundleCollectorSettingData.Setting.EnableAddressable = enableAddressable;
AssetBundleCollectorSettingData.Setting.UniqueBundleName = uniqueBundleName;
AssetBundleCollectorSettingData.Setting.ShowPackageView = showPackageView;
AssetBundleCollectorSettingData.Setting.ShowEditorAlias = showEditorAlias;
AssetBundleCollectorSettingData.Setting.Packages.AddRange(packages);
AssetBundleCollectorSettingData.SaveFile();
Debug.Log($"导入配置完毕!");
}
/// <summary>
/// 导出XML配置表
/// </summary>
public static void ExportXmlConfig(string savePath)
{
if (File.Exists(savePath))
File.Delete(savePath);
StringBuilder sb = new StringBuilder();
sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb.AppendLine("<root>");
sb.AppendLine("</root>");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(sb.ToString());
XmlElement root = xmlDoc.DocumentElement;
// 设置配置版本
root.SetAttribute(XmlVersion, ConfigVersion);
// 设置公共配置
var commonElement = xmlDoc.CreateElement(XmlCommon);
commonElement.SetAttribute(XmlEnableAddressable, AssetBundleCollectorSettingData.Setting.EnableAddressable.ToString());
commonElement.SetAttribute(XmlUniqueBundleName, AssetBundleCollectorSettingData.Setting.UniqueBundleName.ToString());
commonElement.SetAttribute(XmlShowPackageView, AssetBundleCollectorSettingData.Setting.ShowPackageView.ToString());
commonElement.SetAttribute(XmlShowEditorAlias, AssetBundleCollectorSettingData.Setting.ShowEditorAlias.ToString());
root.AppendChild(commonElement);
// 设置Package配置
foreach (var package in AssetBundleCollectorSettingData.Setting.Packages)
{
var packageElement = xmlDoc.CreateElement(XmlPackage);
packageElement.SetAttribute(XmlPackageName, package.PackageName);
packageElement.SetAttribute(XmlPackageDesc, package.PackageDesc);
root.AppendChild(packageElement);
// 设置分组配置
foreach (var group in package.Groups)
{
var groupElement = xmlDoc.CreateElement(XmlGroup);
groupElement.SetAttribute(XmlGroupActiveRule, group.ActiveRuleName);
groupElement.SetAttribute(XmlGroupName, group.GroupName);
groupElement.SetAttribute(XmlGroupDesc, group.GroupDesc);
groupElement.SetAttribute(XmlAssetTags, group.AssetTags);
packageElement.AppendChild(groupElement);
// 设置收集器配置
foreach (var collector in group.Collectors)
{
var collectorElement = xmlDoc.CreateElement(XmlCollector);
collectorElement.SetAttribute(XmlCollectPath, collector.CollectPath);
collectorElement.SetAttribute(XmlCollectorGUID, collector.CollectorGUID);
collectorElement.SetAttribute(XmlCollectorType, collector.CollectorType.ToString());
collectorElement.SetAttribute(XmlAddressRule, collector.AddressRuleName);
collectorElement.SetAttribute(XmlPackRule, collector.PackRuleName);
collectorElement.SetAttribute(XmlFilterRule, collector.FilterRuleName);
collectorElement.SetAttribute(XmlUserData, collector.UserData);
collectorElement.SetAttribute(XmlAssetTags, collector.AssetTags);
groupElement.AppendChild(collectorElement);
}
}
}
// 生成配置文件
xmlDoc.Save(savePath);
Debug.Log($"导出配置完毕!");
}
/// <summary>
/// 升级XML配置表
/// </summary>
private static bool UpdateXmlConfig(XmlDocument xmlDoc)
{
XmlElement root = xmlDoc.DocumentElement;
string configVersion = root.GetAttribute(XmlVersion);
if (configVersion == ConfigVersion)
return true;
// 1.0 -> 2.0
if (configVersion == "1.0")
{
// 添加公共元素属性
var commonNodeList = root.GetElementsByTagName(XmlCommon);
if (commonNodeList.Count > 0)
{
XmlElement commonElement = commonNodeList[0] as XmlElement;
if (commonElement.HasAttribute(XmlShowPackageView) == false)
commonElement.SetAttribute(XmlShowPackageView, "False");
}
// 添加包裹元素
var packageElement = xmlDoc.CreateElement(XmlPackage);
packageElement.SetAttribute(XmlPackageName, "DefaultPackage");
packageElement.SetAttribute(XmlPackageDesc, string.Empty);
root.AppendChild(packageElement);
// 获取所有分组元素
var groupNodeList = root.GetElementsByTagName(XmlGroup);
List<XmlElement> temper = new List<XmlElement>(groupNodeList.Count);
foreach (var groupNode in groupNodeList)
{
XmlElement groupElement = groupNode as XmlElement;
var collectorNodeList = groupElement.GetElementsByTagName(XmlCollector);
foreach (var collectorNode in collectorNodeList)
{
XmlElement collectorElement = collectorNode as XmlElement;
if (collectorElement.HasAttribute(XmlCollectorGUID) == false)
collectorElement.SetAttribute(XmlCollectorGUID, string.Empty);
}
temper.Add(groupElement);
}
// 将分组元素转移至包裹元素下
foreach (var groupElement in temper)
{
root.RemoveChild(groupElement);
packageElement.AppendChild(groupElement);
}
// 更新版本
root.SetAttribute(XmlVersion, "2.0");
return UpdateXmlConfig(xmlDoc);
}
// 2.0 -> 2.1
if (configVersion == "2.0")
{
// 添加公共元素属性
var commonNodeList = root.GetElementsByTagName(XmlCommon);
if (commonNodeList.Count > 0)
{
XmlElement commonElement = commonNodeList[0] as XmlElement;
if (commonElement.HasAttribute(XmlUniqueBundleName) == false)
commonElement.SetAttribute(XmlUniqueBundleName, "False");
}
// 更新版本
root.SetAttribute(XmlVersion, "2.1");
return UpdateXmlConfig(xmlDoc);
}
// 2.1 -> 2.2
if (configVersion == "2.1")
{
// 添加公共元素属性
var commonNodeList = root.GetElementsByTagName(XmlCommon);
if (commonNodeList.Count > 0)
{
XmlElement commonElement = commonNodeList[0] as XmlElement;
if (commonElement.HasAttribute(XmlShowEditorAlias) == false)
commonElement.SetAttribute(XmlShowEditorAlias, "False");
}
// 更新版本
root.SetAttribute(XmlVersion, "2.2");
return UpdateXmlConfig(xmlDoc);
}
// 2.2 -> 2.3
if (configVersion == "2.2")
{
// 获取所有分组元素
var groupNodeList = root.GetElementsByTagName(XmlGroup);
foreach (var groupNode in groupNodeList)
{
XmlElement groupElement = groupNode as XmlElement;
var collectorNodeList = groupElement.GetElementsByTagName(XmlCollector);
foreach (var collectorNode in collectorNodeList)
{
XmlElement collectorElement = collectorNode as XmlElement;
if (collectorElement.HasAttribute(XmlUserData) == false)
collectorElement.SetAttribute(XmlUserData, string.Empty);
}
}
// 更新版本
root.SetAttribute(XmlVersion, "2.3");
return UpdateXmlConfig(xmlDoc);
}
// 2.3 -> 2.4
if(configVersion == "2.3")
{
// 获取所有分组元素
var groupNodeList = root.GetElementsByTagName(XmlGroup);
foreach (var groupNode in groupNodeList)
{
XmlElement groupElement = groupNode as XmlElement;
if(groupElement.HasAttribute(XmlGroupActiveRule) == false)
groupElement.SetAttribute(XmlGroupActiveRule, $"{nameof(EnableGroup)}");
}
// 更新版本
root.SetAttribute(XmlVersion, "2.4");
return UpdateXmlConfig(xmlDoc);
}
return false;
}
}
}

View File

@ -1,118 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
namespace YooAsset.Editor
{
[Serializable]
public class AssetBundleCollectorGroup
{
/// <summary>
/// 分组名称
/// </summary>
public string GroupName = string.Empty;
/// <summary>
/// 分组描述
/// </summary>
public string GroupDesc = string.Empty;
/// <summary>
/// 资源分类标签
/// </summary>
public string AssetTags = string.Empty;
/// <summary>
/// 分组激活规则
/// </summary>
public string ActiveRuleName = nameof(EnableGroup);
/// <summary>
/// 分组的收集器列表
/// </summary>
public List<AssetBundleCollector> Collectors = new List<AssetBundleCollector>();
/// <summary>
/// 检测配置错误
/// </summary>
public void CheckConfigError()
{
if (AssetBundleCollectorSettingData.HasActiveRuleName(ActiveRuleName) == false)
throw new Exception($"Invalid {nameof(IActiveRule)} class type : {ActiveRuleName} in group : {GroupName}");
foreach (var collector in Collectors)
{
collector.CheckConfigError();
}
}
/// <summary>
/// 修复配置错误
/// </summary>
public bool FixConfigError()
{
bool isFixed = false;
foreach (var collector in Collectors)
{
if (collector.FixConfigError())
{
isFixed = true;
}
}
return isFixed;
}
/// <summary>
/// 获取打包收集的资源文件
/// </summary>
public List<CollectAssetInfo> GetAllCollectAssets(CollectCommand command)
{
Dictionary<string, CollectAssetInfo> result = new Dictionary<string, CollectAssetInfo>(10000);
// 检测分组是否激活
IActiveRule activeRule = AssetBundleCollectorSettingData.GetActiveRuleInstance(ActiveRuleName);
if (activeRule.IsActiveGroup() == false)
{
return new List<CollectAssetInfo>();
}
// 收集打包资源
foreach (var collector in Collectors)
{
var temper = collector.GetAllCollectAssets(command, this);
foreach (var assetInfo in temper)
{
if (result.ContainsKey(assetInfo.AssetPath) == false)
result.Add(assetInfo.AssetPath, assetInfo);
else
throw new Exception($"The collecting asset file is existed : {assetInfo.AssetPath} in group : {GroupName}");
}
}
// 检测可寻址地址是否重复
if (command.EnableAddressable)
{
var addressTemper = new Dictionary<string, string>();
foreach (var collectInfoPair in result)
{
if (collectInfoPair.Value.CollectorType == ECollectorType.MainAssetCollector)
{
string address = collectInfoPair.Value.Address;
string assetPath = collectInfoPair.Value.AssetPath;
if (addressTemper.TryGetValue(address, out var existed) == false)
addressTemper.Add(address, assetPath);
else
throw new Exception($"The address is existed : {address} in group : {GroupName} \nAssetPath:\n {existed}\n {assetPath}");
}
}
}
// 返回列表
return result.Values.ToList();
}
}
}

View File

@ -1,126 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
namespace YooAsset.Editor
{
[Serializable]
public class AssetBundleCollectorPackage
{
/// <summary>
/// 包裹名称
/// </summary>
public string PackageName = string.Empty;
/// <summary>
/// 包裹描述
/// </summary>
public string PackageDesc = string.Empty;
/// <summary>
/// 分组列表
/// </summary>
public List<AssetBundleCollectorGroup> Groups = new List<AssetBundleCollectorGroup>();
/// <summary>
/// 检测配置错误
/// </summary>
public void CheckConfigError()
{
foreach (var group in Groups)
{
group.CheckConfigError();
}
}
/// <summary>
/// 修复配置错误
/// </summary>
public bool FixConfigError()
{
bool isFixed = false;
foreach (var group in Groups)
{
if (group.FixConfigError())
{
isFixed = true;
}
}
return isFixed;
}
/// <summary>
/// 获取打包收集的资源文件
/// </summary>
public List<CollectAssetInfo> GetAllCollectAssets(CollectCommand command)
{
Dictionary<string, CollectAssetInfo> result = new Dictionary<string, CollectAssetInfo>(10000);
// 收集打包资源
foreach (var group in Groups)
{
var temper = group.GetAllCollectAssets(command);
foreach (var assetInfo in temper)
{
if (result.ContainsKey(assetInfo.AssetPath) == false)
result.Add(assetInfo.AssetPath, assetInfo);
else
throw new Exception($"The collecting asset file is existed : {assetInfo.AssetPath}");
}
}
// 检测可寻址地址是否重复
if (command.EnableAddressable)
{
var addressTemper = new Dictionary<string, string>();
foreach (var collectInfoPair in result)
{
if (collectInfoPair.Value.CollectorType == ECollectorType.MainAssetCollector)
{
string address = collectInfoPair.Value.Address;
string assetPath = collectInfoPair.Value.AssetPath;
if (addressTemper.TryGetValue(address, out var existed) == false)
addressTemper.Add(address, assetPath);
else
throw new Exception($"The address is existed : {address} \nAssetPath:\n {existed}\n {assetPath}");
}
}
}
// 返回列表
return result.Values.ToList();
}
/// <summary>
/// 获取所有的资源标签
/// </summary>
public List<string> GetAllTags()
{
HashSet<string> result = new HashSet<string>();
foreach (var group in Groups)
{
List<string> groupTags = EditorTools.StringToStringList(group.AssetTags, ';');
foreach (var tag in groupTags)
{
if (result.Contains(tag) == false)
result.Add(tag);
}
foreach (var collector in group.Collectors)
{
List<string> collectorTags = EditorTools.StringToStringList(collector.AssetTags, ';');
foreach (var tag in collectorTags)
{
if (result.Contains(tag) == false)
result.Add(tag);
}
}
}
return result.ToList();
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 154d1124b6089254895b0f2b672394d5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,114 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace YooAsset.Editor
{
[CreateAssetMenu(fileName = "AssetBundleCollectorSetting", menuName = "YooAsset/Create AssetBundle Collector Settings")]
public class AssetBundleCollectorSetting : ScriptableObject
{
/// <summary>
/// 是否显示包裹列表视图
/// </summary>
public bool ShowPackageView = false;
/// <summary>
/// 是否启用可寻址资源定位
/// </summary>
public bool EnableAddressable = false;
/// <summary>
/// 资源包名唯一化
/// </summary>
public bool UniqueBundleName = false;
/// <summary>
/// 是否显示编辑器别名
/// </summary>
public bool ShowEditorAlias = false;
/// <summary>
/// 包裹列表
/// </summary>
public List<AssetBundleCollectorPackage> Packages = new List<AssetBundleCollectorPackage>();
/// <summary>
/// 清空所有数据
/// </summary>
public void ClearAll()
{
EnableAddressable = false;
Packages.Clear();
}
/// <summary>
/// 检测配置错误
/// </summary>
public void CheckConfigError()
{
foreach (var package in Packages)
{
package.CheckConfigError();
}
}
/// <summary>
/// 修复配置错误
/// </summary>
public bool FixConfigError()
{
bool isFixed = false;
foreach (var package in Packages)
{
if (package.FixConfigError())
{
isFixed = true;
}
}
return isFixed;
}
/// <summary>
/// 获取所有的资源标签
/// </summary>
public List<string> GetPackageAllTags(string packageName)
{
foreach (var package in Packages)
{
if (package.PackageName == packageName)
{
return package.GetAllTags();
}
}
Debug.LogWarning($"Not found package : {packageName}");
return new List<string>();
}
/// <summary>
/// 获取包裹收集的资源文件
/// </summary>
public CollectResult GetPackageAssets(EBuildMode buildMode, string packageName)
{
if (string.IsNullOrEmpty(packageName))
throw new Exception("Build package name is null or mepty !");
foreach (var package in Packages)
{
if (package.PackageName == packageName)
{
CollectCommand command = new CollectCommand(buildMode, packageName, EnableAddressable, UniqueBundleName);
CollectResult collectResult = new CollectResult(command);
collectResult.SetCollectAssets(package.GetAllCollectAssets(command));
return collectResult;
}
}
throw new Exception($"Not found collector pacakge : {packageName}");
}
}
}

View File

@ -1,435 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
namespace YooAsset.Editor
{
public class AssetBundleCollectorSettingData
{
private static readonly Dictionary<string, System.Type> _cacheActiveRuleTypes = new Dictionary<string, Type>();
private static readonly Dictionary<string, IActiveRule> _cacheActiveRuleInstance = new Dictionary<string, IActiveRule>();
private static readonly Dictionary<string, System.Type> _cacheAddressRuleTypes = new Dictionary<string, System.Type>();
private static readonly Dictionary<string, IAddressRule> _cacheAddressRuleInstance = new Dictionary<string, IAddressRule>();
private static readonly Dictionary<string, System.Type> _cachePackRuleTypes = new Dictionary<string, System.Type>();
private static readonly Dictionary<string, IPackRule> _cachePackRuleInstance = new Dictionary<string, IPackRule>();
private static readonly Dictionary<string, System.Type> _cacheFilterRuleTypes = new Dictionary<string, System.Type>();
private static readonly Dictionary<string, IFilterRule> _cacheFilterRuleInstance = new Dictionary<string, IFilterRule>();
/// <summary>
/// 配置数据是否被修改
/// </summary>
public static bool IsDirty { private set; get; } = false;
static AssetBundleCollectorSettingData()
{
// IPackRule
{
// 清空缓存集合
_cachePackRuleTypes.Clear();
_cachePackRuleInstance.Clear();
// 获取所有类型
List<Type> types = new List<Type>(100)
{
typeof(PackSeparately),
typeof(PackDirectory),
typeof(PackTopDirectory),
typeof(PackCollector),
typeof(PackGroup),
typeof(PackRawFile),
typeof(PackShaderVariants)
};
var customTypes = EditorTools.GetAssignableTypes(typeof(IPackRule));
types.AddRange(customTypes);
for (int i = 0; i < types.Count; i++)
{
Type type = types[i];
if (_cachePackRuleTypes.ContainsKey(type.Name) == false)
_cachePackRuleTypes.Add(type.Name, type);
}
}
// IFilterRule
{
// 清空缓存集合
_cacheFilterRuleTypes.Clear();
_cacheFilterRuleInstance.Clear();
// 获取所有类型
List<Type> types = new List<Type>(100)
{
typeof(CollectAll),
typeof(CollectScene),
typeof(CollectPrefab),
typeof(CollectSprite)
};
var customTypes = EditorTools.GetAssignableTypes(typeof(IFilterRule));
types.AddRange(customTypes);
for (int i = 0; i < types.Count; i++)
{
Type type = types[i];
if (_cacheFilterRuleTypes.ContainsKey(type.Name) == false)
_cacheFilterRuleTypes.Add(type.Name, type);
}
}
// IAddressRule
{
// 清空缓存集合
_cacheAddressRuleTypes.Clear();
_cacheAddressRuleInstance.Clear();
// 获取所有类型
List<Type> types = new List<Type>(100)
{
typeof(AddressByFileName),
typeof(AddressByFilePath),
typeof(AddressByFolderAndFileName),
typeof(AddressByGroupAndFileName)
};
var customTypes = EditorTools.GetAssignableTypes(typeof(IAddressRule));
types.AddRange(customTypes);
for (int i = 0; i < types.Count; i++)
{
Type type = types[i];
if (_cacheAddressRuleTypes.ContainsKey(type.Name) == false)
_cacheAddressRuleTypes.Add(type.Name, type);
}
}
// IActiveRule
{
// 清空缓存集合
_cacheActiveRuleTypes.Clear();
_cacheActiveRuleInstance.Clear();
// 获取所有类型
List<Type> types = new List<Type>(100)
{
typeof(EnableGroup),
typeof(DisableGroup),
};
var customTypes = EditorTools.GetAssignableTypes(typeof(IActiveRule));
types.AddRange(customTypes);
for (int i = 0; i < types.Count; i++)
{
Type type = types[i];
if (_cacheActiveRuleTypes.ContainsKey(type.Name) == false)
_cacheActiveRuleTypes.Add(type.Name, type);
}
}
}
private static AssetBundleCollectorSetting _setting = null;
public static AssetBundleCollectorSetting Setting
{
get
{
if (_setting == null)
_setting = SettingLoader.LoadSettingData<AssetBundleCollectorSetting>();
return _setting;
}
}
/// <summary>
/// 存储配置文件
/// </summary>
public static void SaveFile()
{
if (Setting != null)
{
IsDirty = false;
EditorUtility.SetDirty(Setting);
AssetDatabase.SaveAssets();
Debug.Log($"{nameof(AssetBundleCollectorSetting)}.asset is saved!");
}
}
/// <summary>
/// 修复配置文件
/// </summary>
public static void FixFile()
{
bool isFixed = Setting.FixConfigError();
if (isFixed)
{
IsDirty = true;
}
}
/// <summary>
/// 清空所有数据
/// </summary>
public static void ClearAll()
{
Setting.ClearAll();
SaveFile();
}
public static List<RuleDisplayName> GetActiveRuleNames()
{
List<RuleDisplayName> names = new List<RuleDisplayName>();
foreach (var pair in _cacheActiveRuleTypes)
{
RuleDisplayName ruleName = new RuleDisplayName();
ruleName.ClassName = pair.Key;
ruleName.DisplayName = GetRuleDisplayName(pair.Key, pair.Value);
names.Add(ruleName);
}
return names;
}
public static List<RuleDisplayName> GetAddressRuleNames()
{
List<RuleDisplayName> names = new List<RuleDisplayName>();
foreach (var pair in _cacheAddressRuleTypes)
{
RuleDisplayName ruleName = new RuleDisplayName();
ruleName.ClassName = pair.Key;
ruleName.DisplayName = GetRuleDisplayName(pair.Key, pair.Value);
names.Add(ruleName);
}
return names;
}
public static List<RuleDisplayName> GetPackRuleNames()
{
List<RuleDisplayName> names = new List<RuleDisplayName>();
foreach (var pair in _cachePackRuleTypes)
{
RuleDisplayName ruleName = new RuleDisplayName();
ruleName.ClassName = pair.Key;
ruleName.DisplayName = GetRuleDisplayName(pair.Key, pair.Value);
names.Add(ruleName);
}
return names;
}
public static List<RuleDisplayName> GetFilterRuleNames()
{
List<RuleDisplayName> names = new List<RuleDisplayName>();
foreach (var pair in _cacheFilterRuleTypes)
{
RuleDisplayName ruleName = new RuleDisplayName();
ruleName.ClassName = pair.Key;
ruleName.DisplayName = GetRuleDisplayName(pair.Key, pair.Value);
names.Add(ruleName);
}
return names;
}
private static string GetRuleDisplayName(string name, Type type)
{
var attribute = DisplayNameAttributeHelper.GetAttribute<DisplayNameAttribute>(type);
if (attribute != null && string.IsNullOrEmpty(attribute.DisplayName) == false)
return attribute.DisplayName;
else
return name;
}
public static bool HasActiveRuleName(string ruleName)
{
return _cacheActiveRuleTypes.Keys.Contains(ruleName);
}
public static bool HasAddressRuleName(string ruleName)
{
return _cacheAddressRuleTypes.Keys.Contains(ruleName);
}
public static bool HasPackRuleName(string ruleName)
{
return _cachePackRuleTypes.Keys.Contains(ruleName);
}
public static bool HasFilterRuleName(string ruleName)
{
return _cacheFilterRuleTypes.Keys.Contains(ruleName);
}
public static IActiveRule GetActiveRuleInstance(string ruleName)
{
if (_cacheActiveRuleInstance.TryGetValue(ruleName, out IActiveRule instance))
return instance;
// 如果不存在创建类的实例
if (_cacheActiveRuleTypes.TryGetValue(ruleName, out Type type))
{
instance = (IActiveRule)Activator.CreateInstance(type);
_cacheActiveRuleInstance.Add(ruleName, instance);
return instance;
}
else
{
throw new Exception($"{nameof(IActiveRule)}类型无效:{ruleName}");
}
}
public static IAddressRule GetAddressRuleInstance(string ruleName)
{
if (_cacheAddressRuleInstance.TryGetValue(ruleName, out IAddressRule instance))
return instance;
// 如果不存在创建类的实例
if (_cacheAddressRuleTypes.TryGetValue(ruleName, out Type type))
{
instance = (IAddressRule)Activator.CreateInstance(type);
_cacheAddressRuleInstance.Add(ruleName, instance);
return instance;
}
else
{
throw new Exception($"{nameof(IAddressRule)}类型无效:{ruleName}");
}
}
public static IPackRule GetPackRuleInstance(string ruleName)
{
if (_cachePackRuleInstance.TryGetValue(ruleName, out IPackRule instance))
return instance;
// 如果不存在创建类的实例
if (_cachePackRuleTypes.TryGetValue(ruleName, out Type type))
{
instance = (IPackRule)Activator.CreateInstance(type);
_cachePackRuleInstance.Add(ruleName, instance);
return instance;
}
else
{
throw new Exception($"{nameof(IPackRule)}类型无效:{ruleName}");
}
}
public static IFilterRule GetFilterRuleInstance(string ruleName)
{
if (_cacheFilterRuleInstance.TryGetValue(ruleName, out IFilterRule instance))
return instance;
// 如果不存在创建类的实例
if (_cacheFilterRuleTypes.TryGetValue(ruleName, out Type type))
{
instance = (IFilterRule)Activator.CreateInstance(type);
_cacheFilterRuleInstance.Add(ruleName, instance);
return instance;
}
else
{
throw new Exception($"{nameof(IFilterRule)}类型无效:{ruleName}");
}
}
// 公共参数编辑相关
public static void ModifyPackageView(bool showPackageView)
{
Setting.ShowPackageView = showPackageView;
IsDirty = true;
}
public static void ModifyAddressable(bool enableAddressable)
{
Setting.EnableAddressable = enableAddressable;
IsDirty = true;
}
public static void ModifyUniqueBundleName(bool uniqueBundleName)
{
Setting.UniqueBundleName = uniqueBundleName;
IsDirty = true;
}
public static void ModifyShowEditorAlias(bool showAlias)
{
Setting.ShowEditorAlias = showAlias;
IsDirty = true;
}
// 资源包裹编辑相关
public static AssetBundleCollectorPackage CreatePackage(string packageName)
{
AssetBundleCollectorPackage package = new AssetBundleCollectorPackage();
package.PackageName = packageName;
Setting.Packages.Add(package);
IsDirty = true;
return package;
}
public static void RemovePackage(AssetBundleCollectorPackage package)
{
if (Setting.Packages.Remove(package))
{
IsDirty = true;
}
else
{
Debug.LogWarning($"Failed remove package : {package.PackageName}");
}
}
public static void ModifyPackage(AssetBundleCollectorPackage package)
{
if (package != null)
{
IsDirty = true;
}
}
// 资源分组编辑相关
public static AssetBundleCollectorGroup CreateGroup(AssetBundleCollectorPackage package, string groupName)
{
AssetBundleCollectorGroup group = new AssetBundleCollectorGroup();
group.GroupName = groupName;
package.Groups.Add(group);
IsDirty = true;
return group;
}
public static void RemoveGroup(AssetBundleCollectorPackage package, AssetBundleCollectorGroup group)
{
if (package.Groups.Remove(group))
{
IsDirty = true;
}
else
{
Debug.LogWarning($"Failed remove group : {group.GroupName}");
}
}
public static void ModifyGroup(AssetBundleCollectorPackage package, AssetBundleCollectorGroup group)
{
if (package != null && group != null)
{
IsDirty = true;
}
}
// 资源收集器编辑相关
public static void CreateCollector(AssetBundleCollectorGroup group, AssetBundleCollector collector)
{
group.Collectors.Add(collector);
IsDirty = true;
}
public static void RemoveCollector(AssetBundleCollectorGroup group, AssetBundleCollector collector)
{
if (group.Collectors.Remove(collector))
{
IsDirty = true;
}
else
{
Debug.LogWarning($"Failed remove collector : {collector.CollectPath}");
}
}
public static void ModifyCollector(AssetBundleCollectorGroup group, AssetBundleCollector collector)
{
if (group != null && collector != null)
{
IsDirty = true;
}
}
/// <summary>
/// 获取所有的资源标签
/// </summary>
public static string GetPackageAllTags(string packageName)
{
var allTags = Setting.GetPackageAllTags(packageName);
return string.Join(";", allTags);
}
}
}

View File

@ -1,900 +0,0 @@
#if UNITY_2019_4_OR_NEWER
using System.IO;
using System.Linq;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace YooAsset.Editor
{
public class AssetBundleCollectorWindow : EditorWindow
{
[MenuItem("YooAsset/AssetBundle Collector", false, 101)]
public static void OpenWindow()
{
AssetBundleCollectorWindow window = GetWindow<AssetBundleCollectorWindow>("资源包收集工具", true, WindowsDefine.DockedWindowTypes);
window.minSize = new Vector2(800, 600);
}
private Button _saveButton;
private List<string> _collectorTypeList;
private List<RuleDisplayName> _activeRuleList;
private List<RuleDisplayName> _addressRuleList;
private List<RuleDisplayName> _packRuleList;
private List<RuleDisplayName> _filterRuleList;
private Toggle _showPackageToogle;
private Toggle _enableAddressableToogle;
private Toggle _uniqueBundleNameToogle;
private Toggle _showEditorAliasToggle;
private VisualElement _packageContainer;
private ListView _packageListView;
private TextField _packageNameTxt;
private TextField _packageDescTxt;
private VisualElement _groupContainer;
private ListView _groupListView;
private TextField _groupNameTxt;
private TextField _groupDescTxt;
private TextField _groupAssetTagsTxt;
private VisualElement _collectorContainer;
private ScrollView _collectorScrollView;
private PopupField<RuleDisplayName> _activeRulePopupField;
private int _lastModifyPackageIndex = 0;
private int _lastModifyGroupIndex = 0;
public void CreateGUI()
{
Undo.undoRedoPerformed -= RefreshWindow;
Undo.undoRedoPerformed += RefreshWindow;
try
{
_collectorTypeList = new List<string>()
{
$"{nameof(ECollectorType.MainAssetCollector)}",
$"{nameof(ECollectorType.StaticAssetCollector)}",
$"{nameof(ECollectorType.DependAssetCollector)}"
};
_activeRuleList = AssetBundleCollectorSettingData.GetActiveRuleNames();
_addressRuleList = AssetBundleCollectorSettingData.GetAddressRuleNames();
_packRuleList = AssetBundleCollectorSettingData.GetPackRuleNames();
_filterRuleList = AssetBundleCollectorSettingData.GetFilterRuleNames();
VisualElement root = this.rootVisualElement;
// 加载布局文件
var visualAsset = UxmlLoader.LoadWindowUXML<AssetBundleCollectorWindow>();
if (visualAsset == null)
return;
visualAsset.CloneTree(root);
// 公共设置相关
_showPackageToogle = root.Q<Toggle>("ShowPackages");
_showPackageToogle.RegisterValueChangedCallback(evt =>
{
AssetBundleCollectorSettingData.ModifyPackageView(evt.newValue);
RefreshWindow();
});
_enableAddressableToogle = root.Q<Toggle>("EnableAddressable");
_enableAddressableToogle.RegisterValueChangedCallback(evt =>
{
AssetBundleCollectorSettingData.ModifyAddressable(evt.newValue);
RefreshWindow();
});
_uniqueBundleNameToogle = root.Q<Toggle>("UniqueBundleName");
_uniqueBundleNameToogle.RegisterValueChangedCallback(evt =>
{
AssetBundleCollectorSettingData.ModifyUniqueBundleName(evt.newValue);
RefreshWindow();
});
_showEditorAliasToggle = root.Q<Toggle>("ShowEditorAlias");
_showEditorAliasToggle.RegisterValueChangedCallback(evt =>
{
AssetBundleCollectorSettingData.ModifyShowEditorAlias(evt.newValue);
RefreshWindow();
});
// 配置修复按钮
var fixBtn = root.Q<Button>("FixButton");
fixBtn.clicked += FixBtn_clicked;
// 导入导出按钮
var exportBtn = root.Q<Button>("ExportButton");
exportBtn.clicked += ExportBtn_clicked;
var importBtn = root.Q<Button>("ImportButton");
importBtn.clicked += ImportBtn_clicked;
// 配置保存按钮
_saveButton = root.Q<Button>("SaveButton");
_saveButton.clicked += SaveBtn_clicked;
// 包裹容器
_packageContainer = root.Q("PackageContainer");
// 包裹列表相关
_packageListView = root.Q<ListView>("PackageListView");
_packageListView.makeItem = MakePackageListViewItem;
_packageListView.bindItem = BindPackageListViewItem;
#if UNITY_2020_1_OR_NEWER
_packageListView.onSelectionChange += PackageListView_onSelectionChange;
#else
_packageListView.onSelectionChanged += PackageListView_onSelectionChange;
#endif
// 包裹添加删除按钮
var packageAddContainer = root.Q("PackageAddContainer");
{
var addBtn = packageAddContainer.Q<Button>("AddBtn");
addBtn.clicked += AddPackageBtn_clicked;
var removeBtn = packageAddContainer.Q<Button>("RemoveBtn");
removeBtn.clicked += RemovePackageBtn_clicked;
}
// 包裹名称
_packageNameTxt = root.Q<TextField>("PackageName");
_packageNameTxt.RegisterValueChangedCallback(evt =>
{
var selectPackage = _packageListView.selectedItem as AssetBundleCollectorPackage;
if (selectPackage != null)
{
selectPackage.PackageName = evt.newValue;
AssetBundleCollectorSettingData.ModifyPackage(selectPackage);
FillPackageViewData();
}
});
// 包裹备注
_packageDescTxt = root.Q<TextField>("PackageDesc");
_packageDescTxt.RegisterValueChangedCallback(evt =>
{
var selectPackage = _packageListView.selectedItem as AssetBundleCollectorPackage;
if (selectPackage != null)
{
selectPackage.PackageDesc = evt.newValue;
AssetBundleCollectorSettingData.ModifyPackage(selectPackage);
FillPackageViewData();
}
});
// 分组列表相关
_groupListView = root.Q<ListView>("GroupListView");
_groupListView.makeItem = MakeGroupListViewItem;
_groupListView.bindItem = BindGroupListViewItem;
#if UNITY_2020_1_OR_NEWER
_groupListView.onSelectionChange += GroupListView_onSelectionChange;
#else
_groupListView.onSelectionChanged += GroupListView_onSelectionChange;
#endif
// 分组添加删除按钮
var groupAddContainer = root.Q("GroupAddContainer");
{
var addBtn = groupAddContainer.Q<Button>("AddBtn");
addBtn.clicked += AddGroupBtn_clicked;
var removeBtn = groupAddContainer.Q<Button>("RemoveBtn");
removeBtn.clicked += RemoveGroupBtn_clicked;
}
// 分组容器
_groupContainer = root.Q("GroupContainer");
// 分组名称
_groupNameTxt = root.Q<TextField>("GroupName");
_groupNameTxt.RegisterValueChangedCallback(evt =>
{
var selectPackage = _packageListView.selectedItem as AssetBundleCollectorPackage;
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectPackage != null && selectGroup != null)
{
selectGroup.GroupName = evt.newValue;
AssetBundleCollectorSettingData.ModifyGroup(selectPackage, selectGroup);
FillGroupViewData();
}
});
// 分组备注
_groupDescTxt = root.Q<TextField>("GroupDesc");
_groupDescTxt.RegisterValueChangedCallback(evt =>
{
var selectPackage = _packageListView.selectedItem as AssetBundleCollectorPackage;
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectPackage != null && selectGroup != null)
{
selectGroup.GroupDesc = evt.newValue;
AssetBundleCollectorSettingData.ModifyGroup(selectPackage, selectGroup);
FillGroupViewData();
}
});
// 分组的资源标签
_groupAssetTagsTxt = root.Q<TextField>("GroupAssetTags");
_groupAssetTagsTxt.RegisterValueChangedCallback(evt =>
{
var selectPackage = _packageListView.selectedItem as AssetBundleCollectorPackage;
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectPackage != null && selectGroup != null)
{
selectGroup.AssetTags = evt.newValue;
AssetBundleCollectorSettingData.ModifyGroup(selectPackage, selectGroup);
}
});
// 收集列表容器
_collectorContainer = root.Q("CollectorContainer");
// 收集列表相关
_collectorScrollView = root.Q<ScrollView>("CollectorScrollView");
_collectorScrollView.style.height = new Length(100, LengthUnit.Percent);
_collectorScrollView.viewDataKey = "scrollView";
// 收集器创建按钮
var collectorAddContainer = root.Q("CollectorAddContainer");
{
var addBtn = collectorAddContainer.Q<Button>("AddBtn");
addBtn.clicked += AddCollectorBtn_clicked;
}
// 分组激活规则
var activeRuleContainer = root.Q("ActiveRuleContainer");
{
_activeRulePopupField = new PopupField<RuleDisplayName>("Active Rule", _activeRuleList, 0);
_activeRulePopupField.name = "ActiveRuleMaskField";
_activeRulePopupField.style.unityTextAlign = TextAnchor.MiddleLeft;
_activeRulePopupField.formatListItemCallback = FormatListItemCallback;
_activeRulePopupField.formatSelectedValueCallback = FormatSelectedValueCallback;
_activeRulePopupField.RegisterValueChangedCallback(evt =>
{
var selectPackage = _packageListView.selectedItem as AssetBundleCollectorPackage;
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectPackage != null && selectGroup != null)
{
selectGroup.ActiveRuleName = evt.newValue.ClassName;
AssetBundleCollectorSettingData.ModifyGroup(selectPackage, selectGroup);
FillGroupViewData();
}
});
activeRuleContainer.Add(_activeRulePopupField);
}
// 刷新窗体
RefreshWindow();
}
catch (System.Exception e)
{
Debug.LogError(e.ToString());
}
}
public void OnDestroy()
{
// 注意:清空所有撤销操作
Undo.ClearAll();
if (AssetBundleCollectorSettingData.IsDirty)
AssetBundleCollectorSettingData.SaveFile();
}
public void Update()
{
if (_saveButton != null)
{
if (AssetBundleCollectorSettingData.IsDirty)
{
if (_saveButton.enabledSelf == false)
_saveButton.SetEnabled(true);
}
else
{
if (_saveButton.enabledSelf)
_saveButton.SetEnabled(false);
}
}
}
private void RefreshWindow()
{
_showPackageToogle.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.ShowPackageView);
_enableAddressableToogle.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.EnableAddressable);
_uniqueBundleNameToogle.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.UniqueBundleName);
_showEditorAliasToggle.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.ShowEditorAlias);
_groupContainer.visible = false;
_collectorContainer.visible = false;
FillPackageViewData();
}
private void FixBtn_clicked()
{
AssetBundleCollectorSettingData.FixFile();
RefreshWindow();
}
private void ExportBtn_clicked()
{
string resultPath = EditorTools.OpenFolderPanel("Export XML", "Assets/");
if (resultPath != null)
{
AssetBundleCollectorConfig.ExportXmlConfig($"{resultPath}/{nameof(AssetBundleCollectorConfig)}.xml");
}
}
private void ImportBtn_clicked()
{
string resultPath = EditorTools.OpenFilePath("Import XML", "Assets/", "xml");
if (resultPath != null)
{
AssetBundleCollectorConfig.ImportXmlConfig(resultPath);
RefreshWindow();
}
}
private void SaveBtn_clicked()
{
AssetBundleCollectorSettingData.SaveFile();
}
private string FormatListItemCallback(RuleDisplayName ruleDisplayName)
{
if (_showEditorAliasToggle.value)
return ruleDisplayName.DisplayName;
else
return ruleDisplayName.ClassName;
}
private string FormatSelectedValueCallback(RuleDisplayName ruleDisplayName)
{
if (_showEditorAliasToggle.value)
return ruleDisplayName.DisplayName;
else
return ruleDisplayName.ClassName;
}
// 包裹列表相关
private void FillPackageViewData()
{
_packageListView.Clear();
_packageListView.ClearSelection();
_packageListView.itemsSource = AssetBundleCollectorSettingData.Setting.Packages;
_packageListView.Rebuild();
if (_lastModifyPackageIndex >= 0 && _lastModifyPackageIndex < _packageListView.itemsSource.Count)
{
_packageListView.selectedIndex = _lastModifyPackageIndex;
}
if (_showPackageToogle.value)
_packageContainer.style.display = DisplayStyle.Flex;
else
_packageContainer.style.display = DisplayStyle.None;
}
private VisualElement MakePackageListViewItem()
{
VisualElement element = new VisualElement();
{
var label = new Label();
label.name = "Label1";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.flexGrow = 1f;
label.style.height = 20f;
element.Add(label);
}
return element;
}
private void BindPackageListViewItem(VisualElement element, int index)
{
var package = AssetBundleCollectorSettingData.Setting.Packages[index];
var textField1 = element.Q<Label>("Label1");
if (string.IsNullOrEmpty(package.PackageDesc))
textField1.text = package.PackageName;
else
textField1.text = $"{package.PackageName} ({package.PackageDesc})";
}
private void PackageListView_onSelectionChange(IEnumerable<object> objs)
{
var selectPackage = _packageListView.selectedItem as AssetBundleCollectorPackage;
if (selectPackage == null)
{
_groupContainer.visible = false;
_collectorContainer.visible = false;
return;
}
_groupContainer.visible = true;
_lastModifyPackageIndex = _packageListView.selectedIndex;
_packageNameTxt.SetValueWithoutNotify(selectPackage.PackageName);
_packageDescTxt.SetValueWithoutNotify(selectPackage.PackageDesc);
FillGroupViewData();
}
private void AddPackageBtn_clicked()
{
Undo.RecordObject(AssetBundleCollectorSettingData.Setting, "YooAsset.AssetBundleCollectorWindow AddPackage");
AssetBundleCollectorSettingData.CreatePackage("DefaultPackage");
FillPackageViewData();
}
private void RemovePackageBtn_clicked()
{
var selectPackage = _packageListView.selectedItem as AssetBundleCollectorPackage;
if (selectPackage == null)
return;
Undo.RecordObject(AssetBundleCollectorSettingData.Setting, "YooAsset.AssetBundleCollectorWindow RemovePackage");
AssetBundleCollectorSettingData.RemovePackage(selectPackage);
FillPackageViewData();
}
// 分组列表相关
private void FillGroupViewData()
{
var selectPackage = _packageListView.selectedItem as AssetBundleCollectorPackage;
if (selectPackage == null)
return;
_groupListView.Clear();
_groupListView.ClearSelection();
_groupListView.itemsSource = selectPackage.Groups;
_groupListView.Rebuild();
if (_lastModifyGroupIndex >= 0 && _lastModifyGroupIndex < _groupListView.itemsSource.Count)
{
_groupListView.selectedIndex = _lastModifyGroupIndex;
}
}
private VisualElement MakeGroupListViewItem()
{
VisualElement element = new VisualElement();
{
var label = new Label();
label.name = "Label1";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.flexGrow = 1f;
label.style.height = 20f;
element.Add(label);
}
return element;
}
private void BindGroupListViewItem(VisualElement element, int index)
{
var selectPackage = _packageListView.selectedItem as AssetBundleCollectorPackage;
if (selectPackage == null)
return;
var group = selectPackage.Groups[index];
var textField1 = element.Q<Label>("Label1");
if (string.IsNullOrEmpty(group.GroupDesc))
textField1.text = group.GroupName;
else
textField1.text = $"{group.GroupName} ({group.GroupDesc})";
// 激活状态
IActiveRule activeRule = AssetBundleCollectorSettingData.GetActiveRuleInstance(group.ActiveRuleName);
bool isActive = activeRule.IsActiveGroup();
textField1.SetEnabled(isActive);
}
private void GroupListView_onSelectionChange(IEnumerable<object> objs)
{
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGroup == null)
{
_collectorContainer.visible = false;
return;
}
_collectorContainer.visible = true;
_lastModifyGroupIndex = _groupListView.selectedIndex;
_activeRulePopupField.SetValueWithoutNotify(GetActiveRuleIndex(selectGroup.ActiveRuleName));
_groupNameTxt.SetValueWithoutNotify(selectGroup.GroupName);
_groupDescTxt.SetValueWithoutNotify(selectGroup.GroupDesc);
_groupAssetTagsTxt.SetValueWithoutNotify(selectGroup.AssetTags);
FillCollectorViewData();
}
private void AddGroupBtn_clicked()
{
var selectPackage = _packageListView.selectedItem as AssetBundleCollectorPackage;
if (selectPackage == null)
return;
Undo.RecordObject(AssetBundleCollectorSettingData.Setting, "YooAsset.AssetBundleCollectorWindow AddGroup");
AssetBundleCollectorSettingData.CreateGroup(selectPackage, "Default Group");
FillGroupViewData();
}
private void RemoveGroupBtn_clicked()
{
var selectPackage = _packageListView.selectedItem as AssetBundleCollectorPackage;
if (selectPackage == null)
return;
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGroup == null)
return;
Undo.RecordObject(AssetBundleCollectorSettingData.Setting, "YooAsset.AssetBundleCollectorWindow RemoveGroup");
AssetBundleCollectorSettingData.RemoveGroup(selectPackage, selectGroup);
FillGroupViewData();
}
// 收集列表相关
private void FillCollectorViewData()
{
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGroup == null)
return;
// 填充数据
_collectorScrollView.Clear();
for (int i = 0; i < selectGroup.Collectors.Count; i++)
{
VisualElement element = MakeCollectorListViewItem();
BindCollectorListViewItem(element, i);
_collectorScrollView.Add(element);
}
}
private VisualElement MakeCollectorListViewItem()
{
VisualElement element = new VisualElement();
VisualElement elementTop = new VisualElement();
elementTop.style.flexDirection = FlexDirection.Row;
element.Add(elementTop);
VisualElement elementBottom = new VisualElement();
elementBottom.style.flexDirection = FlexDirection.Row;
element.Add(elementBottom);
VisualElement elementFoldout = new VisualElement();
elementFoldout.style.flexDirection = FlexDirection.Row;
element.Add(elementFoldout);
VisualElement elementSpace = new VisualElement();
elementSpace.style.flexDirection = FlexDirection.Column;
element.Add(elementSpace);
// Top VisualElement
{
var button = new Button();
button.name = "Button1";
button.text = "-";
button.style.unityTextAlign = TextAnchor.MiddleCenter;
button.style.flexGrow = 0f;
elementTop.Add(button);
}
{
var objectField = new ObjectField();
objectField.name = "ObjectField1";
objectField.label = "Collector";
objectField.objectType = typeof(UnityEngine.Object);
objectField.style.unityTextAlign = TextAnchor.MiddleLeft;
objectField.style.flexGrow = 1f;
elementTop.Add(objectField);
var label = objectField.Q<Label>();
label.style.minWidth = 63;
}
// Bottom VisualElement
{
var label = new Label();
label.style.width = 90;
elementBottom.Add(label);
}
{
var popupField = new PopupField<string>(_collectorTypeList, 0);
popupField.name = "PopupField0";
popupField.style.unityTextAlign = TextAnchor.MiddleLeft;
popupField.style.width = 150;
elementBottom.Add(popupField);
}
if (_enableAddressableToogle.value)
{
var popupField = new PopupField<RuleDisplayName>(_addressRuleList, 0);
popupField.name = "PopupField1";
popupField.style.unityTextAlign = TextAnchor.MiddleLeft;
popupField.style.width = 220;
elementBottom.Add(popupField);
}
{
var popupField = new PopupField<RuleDisplayName>(_packRuleList, 0);
popupField.name = "PopupField2";
popupField.style.unityTextAlign = TextAnchor.MiddleLeft;
popupField.style.width = 220;
elementBottom.Add(popupField);
}
{
var popupField = new PopupField<RuleDisplayName>(_filterRuleList, 0);
popupField.name = "PopupField3";
popupField.style.unityTextAlign = TextAnchor.MiddleLeft;
popupField.style.width = 150;
elementBottom.Add(popupField);
}
{
var textField = new TextField();
textField.name = "TextField0";
textField.label = "UserData";
textField.style.width = 200;
elementBottom.Add(textField);
var label = textField.Q<Label>();
label.style.minWidth = 63;
}
{
var textField = new TextField();
textField.name = "TextField1";
textField.label = "Tags";
textField.style.width = 100;
textField.style.marginLeft = 20;
textField.style.flexGrow = 1;
elementBottom.Add(textField);
var label = textField.Q<Label>();
label.style.minWidth = 40;
}
// Foldout VisualElement
{
var label = new Label();
label.style.width = 90;
elementFoldout.Add(label);
}
{
var foldout = new Foldout();
foldout.name = "Foldout1";
foldout.value = false;
foldout.text = "Main Assets";
elementFoldout.Add(foldout);
}
// Space VisualElement
{
var label = new Label();
label.style.height = 10;
elementSpace.Add(label);
}
return element;
}
private void BindCollectorListViewItem(VisualElement element, int index)
{
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGroup == null)
return;
var collector = selectGroup.Collectors[index];
var collectObject = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(collector.CollectPath);
if (collectObject != null)
collectObject.name = collector.CollectPath;
// Foldout
var foldout = element.Q<Foldout>("Foldout1");
foldout.RegisterValueChangedCallback(evt =>
{
if (evt.newValue)
RefreshFoldout(foldout, selectGroup, collector);
else
foldout.Clear();
});
// Remove Button
var removeBtn = element.Q<Button>("Button1");
removeBtn.clicked += () =>
{
RemoveCollectorBtn_clicked(collector);
};
// Collector Path
var objectField1 = element.Q<ObjectField>("ObjectField1");
objectField1.SetValueWithoutNotify(collectObject);
objectField1.RegisterValueChangedCallback(evt =>
{
collector.CollectPath = AssetDatabase.GetAssetPath(evt.newValue);
collector.CollectorGUID = AssetDatabase.AssetPathToGUID(collector.CollectPath);
objectField1.value.name = collector.CollectPath;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
});
// Collector Type
var popupField0 = element.Q<PopupField<string>>("PopupField0");
popupField0.index = GetCollectorTypeIndex(collector.CollectorType.ToString());
popupField0.RegisterValueChangedCallback(evt =>
{
collector.CollectorType = EditorTools.NameToEnum<ECollectorType>(evt.newValue);
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
});
// Address Rule
var popupField1 = element.Q<PopupField<RuleDisplayName>>("PopupField1");
if (popupField1 != null)
{
popupField1.index = GetAddressRuleIndex(collector.AddressRuleName);
popupField1.formatListItemCallback = FormatListItemCallback;
popupField1.formatSelectedValueCallback = FormatSelectedValueCallback;
popupField1.RegisterValueChangedCallback(evt =>
{
collector.AddressRuleName = evt.newValue.ClassName;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
});
}
// Pack Rule
var popupField2 = element.Q<PopupField<RuleDisplayName>>("PopupField2");
popupField2.index = GetPackRuleIndex(collector.PackRuleName);
popupField2.formatListItemCallback = FormatListItemCallback;
popupField2.formatSelectedValueCallback = FormatSelectedValueCallback;
popupField2.RegisterValueChangedCallback(evt =>
{
collector.PackRuleName = evt.newValue.ClassName;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
});
// Filter Rule
var popupField3 = element.Q<PopupField<RuleDisplayName>>("PopupField3");
popupField3.index = GetFilterRuleIndex(collector.FilterRuleName);
popupField3.formatListItemCallback = FormatListItemCallback;
popupField3.formatSelectedValueCallback = FormatSelectedValueCallback;
popupField3.RegisterValueChangedCallback(evt =>
{
collector.FilterRuleName = evt.newValue.ClassName;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
});
// UserData
var textFiled0 = element.Q<TextField>("TextField0");
textFiled0.SetValueWithoutNotify(collector.UserData);
textFiled0.RegisterValueChangedCallback(evt =>
{
collector.UserData = evt.newValue;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
});
// Tags
var textFiled1 = element.Q<TextField>("TextField1");
textFiled1.SetValueWithoutNotify(collector.AssetTags);
textFiled1.RegisterValueChangedCallback(evt =>
{
collector.AssetTags = evt.newValue;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
});
}
private void RefreshFoldout(Foldout foldout, AssetBundleCollectorGroup group, AssetBundleCollector collector)
{
// 清空旧元素
foldout.Clear();
if (collector.IsValid() == false)
{
Debug.LogWarning($"The collector is invalid : {collector.CollectPath} in group : {group.GroupName}");
return;
}
if (collector.CollectorType == ECollectorType.MainAssetCollector || collector.CollectorType == ECollectorType.StaticAssetCollector)
{
List<CollectAssetInfo> collectAssetInfos = null;
try
{
CollectCommand command = new CollectCommand(EBuildMode.SimulateBuild, _packageNameTxt.value, _enableAddressableToogle.value, _uniqueBundleNameToogle.value);
collectAssetInfos = collector.GetAllCollectAssets(command, group);
}
catch (System.Exception e)
{
Debug.LogError(e.ToString());
}
if (collectAssetInfos != null)
{
foreach (var collectAssetInfo in collectAssetInfos)
{
VisualElement elementRow = new VisualElement();
elementRow.style.flexDirection = FlexDirection.Row;
foldout.Add(elementRow);
string showInfo = collectAssetInfo.AssetPath;
if (_enableAddressableToogle.value)
showInfo = $"[{collectAssetInfo.Address}] {collectAssetInfo.AssetPath}";
var label = new Label();
label.text = showInfo;
label.style.width = 300;
label.style.marginLeft = 0;
label.style.flexGrow = 1;
elementRow.Add(label);
}
}
}
}
private void AddCollectorBtn_clicked()
{
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGroup == null)
return;
Undo.RecordObject(AssetBundleCollectorSettingData.Setting, "YooAsset.AssetBundleCollectorWindow AddCollector");
AssetBundleCollector collector = new AssetBundleCollector();
AssetBundleCollectorSettingData.CreateCollector(selectGroup, collector);
FillCollectorViewData();
}
private void RemoveCollectorBtn_clicked(AssetBundleCollector selectCollector)
{
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGroup == null)
return;
if (selectCollector == null)
return;
Undo.RecordObject(AssetBundleCollectorSettingData.Setting, "YooAsset.AssetBundleCollectorWindow RemoveCollector");
AssetBundleCollectorSettingData.RemoveCollector(selectGroup, selectCollector);
FillCollectorViewData();
}
private int GetCollectorTypeIndex(string typeName)
{
for (int i = 0; i < _collectorTypeList.Count; i++)
{
if (_collectorTypeList[i] == typeName)
return i;
}
return 0;
}
private int GetAddressRuleIndex(string ruleName)
{
for (int i = 0; i < _addressRuleList.Count; i++)
{
if (_addressRuleList[i].ClassName == ruleName)
return i;
}
return 0;
}
private int GetPackRuleIndex(string ruleName)
{
for (int i = 0; i < _packRuleList.Count; i++)
{
if (_packRuleList[i].ClassName == ruleName)
return i;
}
return 0;
}
private int GetFilterRuleIndex(string ruleName)
{
for (int i = 0; i < _filterRuleList.Count; i++)
{
if (_filterRuleList[i].ClassName == ruleName)
return i;
}
return 0;
}
private RuleDisplayName GetActiveRuleIndex(string ruleName)
{
for (int i = 0; i < _activeRuleList.Count; i++)
{
if (_activeRuleList[i].ClassName == ruleName)
return _activeRuleList[i];
}
return _activeRuleList[0];
}
}
}
#endif

View File

@ -1,45 +0,0 @@
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements">
<uie:Toolbar name="Toolbar" style="display: flex; flex-direction: row-reverse;">
<ui:Button text="Save" display-tooltip-when-elided="true" name="SaveButton" style="width: 50px; background-color: rgb(56, 147, 58);" />
<ui:Button text="导出" display-tooltip-when-elided="true" name="ExportButton" style="width: 50px; background-color: rgb(56, 147, 58);" />
<ui:Button text="导入" display-tooltip-when-elided="true" name="ImportButton" style="width: 50px; background-color: rgb(56, 147, 58);" />
<ui:Button text="修复" display-tooltip-when-elided="true" name="FixButton" style="width: 50px; background-color: rgb(56, 147, 58);" />
</uie:Toolbar>
<ui:VisualElement name="PublicContainer" style="height: 30px; background-color: rgb(67, 67, 67); flex-direction: row; border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; border-bottom-width: 5px;">
<ui:Toggle label="Show Packages" name="ShowPackages" style="width: 196px; -unity-text-align: middle-left;" />
<ui:Toggle label="Show Editor Alias" name="ShowEditorAlias" style="width: 196px; -unity-text-align: middle-left;" />
<ui:Toggle label="Enable Addressable" name="EnableAddressable" style="width: 196px; -unity-text-align: middle-left;" />
<ui:Toggle label="Unique Bundle Name" name="UniqueBundleName" style="width: 196px; -unity-text-align: middle-left;" />
</ui:VisualElement>
<ui:VisualElement name="ContentContainer" style="flex-grow: 1; flex-direction: row;">
<ui:VisualElement name="PackageContainer" style="width: 200px; flex-grow: 0; background-color: rgb(67, 67, 67); border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; border-bottom-width: 5px;">
<ui:Label text="Packages" display-tooltip-when-elided="true" name="PackageTitle" style="background-color: rgb(89, 89, 89); -unity-text-align: upper-center; -unity-font-style: bold; border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; border-bottom-width: 5px; font-size: 12px;" />
<ui:ListView focusable="true" name="PackageListView" item-height="20" virtualization-method="DynamicHeight" style="flex-grow: 1;" />
<ui:VisualElement name="PackageAddContainer" style="height: 20px; flex-direction: row; justify-content: center;">
<ui:Button text=" - " display-tooltip-when-elided="true" name="RemoveBtn" />
<ui:Button text=" + " display-tooltip-when-elided="true" name="AddBtn" />
</ui:VisualElement>
</ui:VisualElement>
<ui:VisualElement name="GroupContainer" style="width: 200px; flex-grow: 0; background-color: rgb(67, 67, 67); border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; border-bottom-width: 5px;">
<ui:Label text="Groups" display-tooltip-when-elided="true" name="GroupTitle" style="background-color: rgb(89, 89, 89); -unity-text-align: upper-center; -unity-font-style: bold; border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; border-bottom-width: 5px; font-size: 12px;" />
<ui:TextField picking-mode="Ignore" label="Package Name" value="filler text" name="PackageName" style="flex-direction: column;" />
<ui:TextField picking-mode="Ignore" label="Package Desc" value="filler text" name="PackageDesc" style="flex-direction: column;" />
<ui:ListView focusable="true" name="GroupListView" item-height="20" virtualization-method="DynamicHeight" style="flex-grow: 1;" />
<ui:VisualElement name="GroupAddContainer" style="height: 20px; flex-direction: row; justify-content: center;">
<ui:Button text=" - " display-tooltip-when-elided="true" name="RemoveBtn" />
<ui:Button text=" + " display-tooltip-when-elided="true" name="AddBtn" />
</ui:VisualElement>
</ui:VisualElement>
<ui:VisualElement name="CollectorContainer" style="flex-grow: 1; border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; border-bottom-width: 5px;">
<ui:Label text="Collectors" display-tooltip-when-elided="true" name="CollectorTitle" style="background-color: rgb(89, 89, 89); -unity-text-align: upper-center; -unity-font-style: bold; border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; border-bottom-width: 5px; font-size: 12px;" />
<ui:VisualElement name="ActiveRuleContainer" style="height: 20px;" />
<ui:TextField picking-mode="Ignore" label="Group Name" name="GroupName" />
<ui:TextField picking-mode="Ignore" label="Group Desc" name="GroupDesc" />
<ui:TextField picking-mode="Ignore" label="Group Asset Tags" name="GroupAssetTags" />
<ui:VisualElement name="CollectorAddContainer" style="height: 20px; flex-direction: row-reverse;">
<ui:Button text="[ + ]" display-tooltip-when-elided="true" name="AddBtn" />
</ui:VisualElement>
<ui:ScrollView name="CollectorScrollView" style="flex-grow: 1;" />
</ui:VisualElement>
</ui:VisualElement>
</ui:UXML>

View File

@ -1,44 +0,0 @@

namespace YooAsset.Editor
{
public class CollectCommand
{
/// <summary>
/// 构建模式
/// </summary>
public EBuildMode BuildMode { private set; get; }
/// <summary>
/// 包裹名称
/// </summary>
public string PackageName { private set; get; }
/// <summary>
/// 是否启用可寻址资源定位
/// </summary>
public bool EnableAddressable { private set; get; }
/// <summary>
/// 资源包名唯一化
/// </summary>
public bool UniqueBundleName { private set; get; }
/// <summary>
/// 着色器统一全名称
/// </summary>
public string ShadersBundleName { private set; get; }
public CollectCommand(EBuildMode buildMode, string packageName, bool enableAddressable, bool uniqueBundleName)
{
BuildMode = buildMode;
PackageName = packageName;
EnableAddressable = enableAddressable;
UniqueBundleName = uniqueBundleName;
// 着色器统一全名称
var packRuleResult = DefaultPackRule.CreateShadersPackRuleResult();
ShadersBundleName = packRuleResult.GetMainBundleName(packageName, uniqueBundleName);
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: b1741e85d76b28d41a4da3cd0e3e6f20
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,27 +0,0 @@
using System.Collections;
using System.Collections.Generic;
namespace YooAsset.Editor
{
public class CollectResult
{
/// <summary>
/// 收集命令
/// </summary>
public CollectCommand Command { private set; get; }
/// <summary>
/// 收集的资源信息列表
/// </summary>
public List<CollectAssetInfo> CollectAssets { private set; get; }
public CollectResult(CollectCommand command)
{
Command = command;
}
public void SetCollectAssets(List<CollectAssetInfo> collectAssets)
{
CollectAssets = collectAssets;
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: dbbd465f929ee33408441b62d19c7d10
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,21 +0,0 @@

namespace YooAsset.Editor
{
[DisplayName("启用分组")]
public class EnableGroup : IActiveRule
{
public bool IsActiveGroup()
{
return true;
}
}
[DisplayName("禁用分组")]
public class DisableGroup : IActiveRule
{
public bool IsActiveGroup()
{
return false;
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 2cfd65b3b7663b247b2df16077f4ef17
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,43 +0,0 @@
using System.IO;
namespace YooAsset.Editor
{
[DisplayName("定位地址: 文件名")]
public class AddressByFileName : IAddressRule
{
string IAddressRule.GetAssetAddress(AddressRuleData data)
{
return Path.GetFileNameWithoutExtension(data.AssetPath);
}
}
[DisplayName("定位地址: 文件路径")]
public class AddressByFilePath : IAddressRule
{
string IAddressRule.GetAssetAddress(AddressRuleData data)
{
return data.AssetPath;
}
}
[DisplayName("定位地址: 分组名+文件名")]
public class AddressByGroupAndFileName : IAddressRule
{
string IAddressRule.GetAssetAddress(AddressRuleData data)
{
string fileName = Path.GetFileNameWithoutExtension(data.AssetPath);
return $"{data.GroupName}_{fileName}";
}
}
[DisplayName("定位地址: 文件夹名+文件名")]
public class AddressByFolderAndFileName : IAddressRule
{
string IAddressRule.GetAssetAddress(AddressRuleData data)
{
string fileName = Path.GetFileNameWithoutExtension(data.AssetPath);
FileInfo fileInfo = new FileInfo(data.AssetPath);
return $"{fileInfo.Directory.Name}_{fileName}";
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 6df37bfd87103a54ca60c0c467a5f33b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,81 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEditor;
namespace YooAsset.Editor
{
public class DefaultFilterRule
{
/// <summary>
/// 忽略的文件类型
/// </summary>
private readonly static HashSet<string> _ignoreFileExtensions = new HashSet<string>() { "", ".so", ".dll", ".cs", ".js", ".boo", ".meta", ".cginc", ".hlsl" };
/// <summary>
/// 查询是否为忽略文件
/// </summary>
public static bool IsIgnoreFile(string fileExtension)
{
return _ignoreFileExtensions.Contains(fileExtension);
}
}
[DisplayName("收集所有资源")]
public class CollectAll : IFilterRule
{
public bool IsCollectAsset(FilterRuleData data)
{
return true;
}
}
[DisplayName("收集场景")]
public class CollectScene : IFilterRule
{
public bool IsCollectAsset(FilterRuleData data)
{
return Path.GetExtension(data.AssetPath) == ".unity";
}
}
[DisplayName("收集预制体")]
public class CollectPrefab : IFilterRule
{
public bool IsCollectAsset(FilterRuleData data)
{
return Path.GetExtension(data.AssetPath) == ".prefab";
}
}
[DisplayName("收集精灵类型的纹理")]
public class CollectSprite : IFilterRule
{
public bool IsCollectAsset(FilterRuleData data)
{
var mainAssetType = AssetDatabase.GetMainAssetTypeAtPath(data.AssetPath);
if (mainAssetType == typeof(Texture2D))
{
var texImporter = AssetImporter.GetAtPath(data.AssetPath) as TextureImporter;
if (texImporter != null && texImporter.textureType == TextureImporterType.Sprite)
return true;
else
return false;
}
else
{
return false;
}
}
}
[DisplayName("收集着色器变种集合")]
public class CollectShaderVariants : IFilterRule
{
public bool IsCollectAsset(FilterRuleData data)
{
return Path.GetExtension(data.AssetPath) == ".shadervariants";
}
}
}

View File

@ -1,196 +0,0 @@
using System;
using System.IO;
using UnityEditor;
namespace YooAsset.Editor
{
public class DefaultPackRule
{
/// <summary>
/// AssetBundle文件的后缀名
/// </summary>
public const string AssetBundleFileExtension = "bundle";
/// <summary>
/// 原生文件的后缀名
/// </summary>
public const string RawFileExtension = "rawfile";
/// <summary>
/// Unity着色器资源包名称
/// </summary>
public const string ShadersBundleName = "unityshaders";
public static PackRuleResult CreateShadersPackRuleResult()
{
PackRuleResult result = new PackRuleResult(ShadersBundleName, AssetBundleFileExtension);
return result;
}
}
/// <summary>
/// 以文件路径作为资源包名
/// 注意:每个文件独自打资源包
/// 例如:"Assets/UIPanel/Shop/Image/backgroud.png" --> "assets_uipanel_shop_image_backgroud.bundle"
/// 例如:"Assets/UIPanel/Shop/View/main.prefab" --> "assets_uipanel_shop_view_main.bundle"
/// </summary>
[DisplayName("资源包名: 文件路径")]
public class PackSeparately : IPackRule
{
PackRuleResult IPackRule.GetPackRuleResult(PackRuleData data)
{
string bundleName = PathUtility.RemoveExtension(data.AssetPath);
PackRuleResult result = new PackRuleResult(bundleName, DefaultPackRule.AssetBundleFileExtension);
return result;
}
bool IPackRule.IsRawFilePackRule()
{
return false;
}
}
/// <summary>
/// 以父类文件夹路径作为资源包名
/// 注意:文件夹下所有文件打进一个资源包
/// 例如:"Assets/UIPanel/Shop/Image/backgroud.png" --> "assets_uipanel_shop_image.bundle"
/// 例如:"Assets/UIPanel/Shop/View/main.prefab" --> "assets_uipanel_shop_view.bundle"
/// </summary>
[DisplayName("资源包名: 父类文件夹路径")]
public class PackDirectory : IPackRule
{
PackRuleResult IPackRule.GetPackRuleResult(PackRuleData data)
{
string bundleName = Path.GetDirectoryName(data.AssetPath);
PackRuleResult result = new PackRuleResult(bundleName, DefaultPackRule.AssetBundleFileExtension);
return result;
}
bool IPackRule.IsRawFilePackRule()
{
return false;
}
}
/// <summary>
/// 以收集器路径下顶级文件夹为资源包名
/// 注意:文件夹下所有文件打进一个资源包
/// 例如:收集器路径为 "Assets/UIPanel"
/// 例如:"Assets/UIPanel/Shop/Image/backgroud.png" --> "assets_uipanel_shop.bundle"
/// 例如:"Assets/UIPanel/Shop/View/main.prefab" --> "assets_uipanel_shop.bundle"
/// </summary>
[DisplayName("资源包名: 收集器下顶级文件夹路径")]
public class PackTopDirectory : IPackRule
{
PackRuleResult IPackRule.GetPackRuleResult(PackRuleData data)
{
string assetPath = data.AssetPath.Replace(data.CollectPath, string.Empty);
assetPath = assetPath.TrimStart('/');
string[] splits = assetPath.Split('/');
if (splits.Length > 0)
{
if (Path.HasExtension(splits[0]))
throw new Exception($"Not found root directory : {assetPath}");
string bundleName = $"{data.CollectPath}/{splits[0]}";
PackRuleResult result = new PackRuleResult(bundleName, DefaultPackRule.AssetBundleFileExtension);
return result;
}
else
{
throw new Exception($"Not found root directory : {assetPath}");
}
}
bool IPackRule.IsRawFilePackRule()
{
return false;
}
}
/// <summary>
/// 以收集器路径作为资源包名
/// 注意:收集的所有文件打进一个资源包
/// </summary>
[DisplayName("资源包名: 收集器路径")]
public class PackCollector : IPackRule
{
PackRuleResult IPackRule.GetPackRuleResult(PackRuleData data)
{
string bundleName;
string collectPath = data.CollectPath;
if (AssetDatabase.IsValidFolder(collectPath))
{
bundleName = collectPath;
}
else
{
bundleName = PathUtility.RemoveExtension(collectPath);
}
PackRuleResult result = new PackRuleResult(bundleName, DefaultPackRule.AssetBundleFileExtension);
return result;
}
bool IPackRule.IsRawFilePackRule()
{
return false;
}
}
/// <summary>
/// 以分组名称作为资源包名
/// 注意:收集的所有文件打进一个资源包
/// </summary>
[DisplayName("资源包名: 分组名称")]
public class PackGroup : IPackRule
{
PackRuleResult IPackRule.GetPackRuleResult(PackRuleData data)
{
string bundleName = data.GroupName;
PackRuleResult result = new PackRuleResult(bundleName, DefaultPackRule.AssetBundleFileExtension);
return result;
}
bool IPackRule.IsRawFilePackRule()
{
return false;
}
}
/// <summary>
/// 打包原生文件
/// </summary>
[DisplayName("打包原生文件")]
public class PackRawFile : IPackRule
{
PackRuleResult IPackRule.GetPackRuleResult(PackRuleData data)
{
string bundleName = data.AssetPath;
PackRuleResult result = new PackRuleResult(bundleName, DefaultPackRule.RawFileExtension);
return result;
}
bool IPackRule.IsRawFilePackRule()
{
return true;
}
}
/// <summary>
/// 打包着色器变种集合
/// </summary>
[DisplayName("打包着色器变种集合文件")]
public class PackShaderVariants : IPackRule
{
public PackRuleResult GetPackRuleResult(PackRuleData data)
{
return DefaultPackRule.CreateShadersPackRuleResult();
}
bool IPackRule.IsRawFilePackRule()
{
return false;
}
}
}

View File

@ -1,16 +0,0 @@
using System;
using System.IO;
using UnityEditor;
namespace YooAsset.Editor
{
public class DefaultShareAssetPackRule : IShareAssetPackRule
{
public PackRuleResult GetPackRuleResult(string assetPath)
{
string bundleName = Path.GetDirectoryName(assetPath);
PackRuleResult result = new PackRuleResult(bundleName, DefaultPackRule.AssetBundleFileExtension);
return result;
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 3b8606481370397489cb3aa21e726d9a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,36 +0,0 @@
using System;
using System.Reflection;
namespace YooAsset.Editor
{
/// <summary>
/// 编辑器显示名字
/// </summary>
public class DisplayNameAttribute : Attribute
{
public string DisplayName;
public DisplayNameAttribute(string name)
{
this.DisplayName = name;
}
}
public static class DisplayNameAttributeHelper
{
internal static T GetAttribute<T>(Type type) where T : Attribute
{
return (T)type.GetCustomAttribute(typeof(T), false);
}
internal static T GetAttribute<T>(MethodInfo methodInfo) where T : Attribute
{
return (T)methodInfo.GetCustomAttribute(typeof(T), false);
}
internal static T GetAttribute<T>(FieldInfo field) where T : Attribute
{
return (T)field.GetCustomAttribute(typeof(T), false);
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 92d5f73b21059af43b7f56165b7acd63
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,29 +0,0 @@
using System;
namespace YooAsset.Editor
{
[Serializable]
public enum ECollectorType
{
/// <summary>
/// 收集参与打包的主资源对象,并写入到资源清单的资源列表里(可以通过代码加载)。
/// </summary>
MainAssetCollector,
/// <summary>
/// 收集参与打包的主资源对象,但不写入到资源清单的资源列表里(无法通过代码加载)。
/// </summary>
StaticAssetCollector,
/// <summary>
/// 收集参与打包的依赖资源对象,但不写入到资源清单的资源列表里(无法通过代码加载)。
/// 注意:如果依赖资源对象没有被主资源对象引用,则不参与打包构建。
/// </summary>
DependAssetCollector,
/// <summary>
/// 该收集器类型不能被设置
/// </summary>
None,
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 4bbef9cb5c1a40b41a28a65df3449abe
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,14 +0,0 @@

namespace YooAsset.Editor
{
/// <summary>
/// 资源分组激活规则接口
/// </summary>
public interface IActiveRule
{
/// <summary>
/// 是否激活分组
/// </summary>
bool IsActiveGroup();
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: aed5a1a6733b7d44ca4f6149ed5a2bb8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,27 +0,0 @@

namespace YooAsset.Editor
{
public struct AddressRuleData
{
public string AssetPath;
public string CollectPath;
public string GroupName;
public string UserData;
public AddressRuleData(string assetPath, string collectPath, string groupName, string userData)
{
AssetPath = assetPath;
CollectPath = collectPath;
GroupName = groupName;
UserData = userData;
}
}
/// <summary>
/// 寻址规则接口
/// </summary>
public interface IAddressRule
{
string GetAssetAddress(AddressRuleData data);
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 426a4ff47699b6844946329f54a89128
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,82 +0,0 @@

namespace YooAsset.Editor
{
public struct PackRuleData
{
public string AssetPath;
public string CollectPath;
public string GroupName;
public string UserData;
public PackRuleData(string assetPath)
{
AssetPath = assetPath;
CollectPath = string.Empty;
GroupName = string.Empty;
UserData = string.Empty;
}
public PackRuleData(string assetPath, string collectPath, string groupName, string userData)
{
AssetPath = assetPath;
CollectPath = collectPath;
GroupName = groupName;
UserData = userData;
}
}
public struct PackRuleResult
{
private readonly string _bundleName;
private readonly string _bundleExtension;
public PackRuleResult(string bundleName, string bundleExtension)
{
_bundleName = bundleName;
_bundleExtension = bundleExtension;
}
/// <summary>
/// 获取主资源包全名称
/// </summary>
public string GetMainBundleName(string packageName, bool uniqueBundleName)
{
string fullName;
string bundleName = EditorTools.GetRegularPath(_bundleName).Replace('/', '_').Replace('.', '_').ToLower();
if (uniqueBundleName)
fullName = $"{packageName}_{bundleName}.{_bundleExtension}";
else
fullName = $"{bundleName}.{_bundleExtension}";
return fullName.ToLower();
}
/// <summary>
/// 获取共享资源包全名称
/// </summary>
public string GetShareBundleName(string packageName, bool uniqueBundleName)
{
string fullName;
string bundleName = EditorTools.GetRegularPath(_bundleName).Replace('/', '_').Replace('.', '_').ToLower();
if (uniqueBundleName)
fullName = $"{packageName}_share_{bundleName}.{_bundleExtension}";
else
fullName = $"share_{bundleName}.{_bundleExtension}";
return fullName.ToLower();
}
}
/// <summary>
/// 资源打包规则接口
/// </summary>
public interface IPackRule
{
/// <summary>
/// 获取打包规则结果
/// </summary>
PackRuleResult GetPackRuleResult(PackRuleData data);
/// <summary>
/// 是否为原生文件打包规则
/// </summary>
bool IsRawFilePackRule();
}
}

View File

@ -1,14 +0,0 @@

namespace YooAsset.Editor
{
/// <summary>
/// 共享资源的打包规则
/// </summary>
public interface IShareAssetPackRule
{
/// <summary>
/// 获取打包规则结果
/// </summary>
PackRuleResult GetPackRuleResult(string assetPath);
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 1ed930b0cc1db1742b0a131ca476bd82
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,9 +0,0 @@

namespace YooAsset.Editor
{
public class RuleDisplayName
{
public string ClassName;
public string DisplayName;
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: df712711c3830af419b7ada8fee53dda
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,328 +1,141 @@
#if UNITY_2019_4_OR_NEWER #if UNITY_2019_4_OR_NEWER
using System;
using System.Collections.Generic;
using UnityEditor; using UnityEditor;
using UnityEngine; using UnityEngine;
using UnityEngine.UIElements; using UnityEngine.UIElements;
using UnityEditor.UIElements; using UnityEditor.UIElements;
using UnityEditor.Networking.PlayerConnection;
using UnityEngine.Networking.PlayerConnection;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
public class AssetBundleDebuggerWindow : EditorWindow public class AssetBundleDebuggerWindow : EditorWindow
{ {
[MenuItem("YooAsset/AssetBundle Debugger", false, 104)] [MenuItem("YooAsset/AssetBundle Debugger", false, 104)]
public static void OpenWindow() public static void ShowExample()
{ {
AssetBundleDebuggerWindow wnd = GetWindow<AssetBundleDebuggerWindow>("资源包调试工具", true, WindowsDefine.DockedWindowTypes); AssetBundleDebuggerWindow wnd = GetWindow<AssetBundleDebuggerWindow>();
wnd.minSize = new Vector2(800, 600); wnd.titleContent = new GUIContent("资源包调试工具");
} wnd.minSize = new Vector2(800, 600);
}
/// <summary> /// <summary>
/// 视图模式 /// 视图模式
/// </summary> /// </summary>
private enum EViewMode private enum EViewMode
{ {
/// <summary> /// <summary>
/// 内存视图 /// 内存视图
/// </summary> /// </summary>
MemoryView, MemoryView,
/// <summary> /// <summary>
/// 资源对象视图 /// 资源对象视图
/// </summary> /// </summary>
AssetView, AssetView,
/// <summary> /// <summary>
/// 资源包视图 /// 资源包视图
/// </summary> /// </summary>
BundleView, BundleView,
} }
private ToolbarMenu _viewModeMenu;
private AssetListDebuggerViewer _assetListViewer;
private BundleListDebuggerViewer _bundleListViewer;
private EViewMode _viewMode;
private readonly DebugReport _debugReport = new DebugReport();
private string _searchKeyWord;
private readonly Dictionary<int, RemotePlayerSession> _playerSessions = new Dictionary<int, RemotePlayerSession>(); public void CreateGUI()
{
VisualElement root = rootVisualElement;
private Label _playerName; // 加载布局文件
private ToolbarMenu _viewModeMenu; string rootPath = EditorTools.GetYooAssetPath();
private SliderInt _frameSlider; string uxml = $"{rootPath}/Editor/AssetBundleDebugger/{nameof(AssetBundleDebuggerWindow)}.uxml";
private DebuggerAssetListViewer _assetListViewer; var visualAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxml);
private DebuggerBundleListViewer _bundleListViewer; if (visualAsset == null)
{
Debug.LogError($"Not found {nameof(AssetBundleDebuggerWindow)}.uxml : {uxml}");
return;
}
visualAsset.CloneTree(root);
private EViewMode _viewMode; // 采样按钮
private string _searchKeyWord; var sampleBtn = root.Q<Button>("SampleButton");
private DebugReport _currentReport; sampleBtn.clicked += SampleBtn_onClick;
private RemotePlayerSession _currentPlayerSession;
private int _rangeIndex = 0;
// 视口模式菜单
_viewModeMenu = root.Q<ToolbarMenu>("ViewModeMenu");
//_viewModeMenu.menu.AppendAction(EViewMode.MemoryView.ToString(), ViewModeMenuAction0, ViewModeMenuFun0);
_viewModeMenu.menu.AppendAction(EViewMode.AssetView.ToString(), ViewModeMenuAction1, ViewModeMenuFun1);
_viewModeMenu.menu.AppendAction(EViewMode.BundleView.ToString(), ViewModeMenuAction2, ViewModeMenuFun2);
public void CreateGUI() // 搜索栏
{ var searchField = root.Q<ToolbarSearchField>("SearchField");
try searchField.RegisterValueChangedCallback(OnSearchKeyWordChange);
{
VisualElement root = rootVisualElement;
// 加载布局文件 // 加载视图
var visualAsset = UxmlLoader.LoadWindowUXML<AssetBundleDebuggerWindow>(); _assetListViewer = new AssetListDebuggerViewer();
if (visualAsset == null) _assetListViewer.InitViewer();
return;
visualAsset.CloneTree(root); // 加载视图
_bundleListViewer = new BundleListDebuggerViewer();
_bundleListViewer.InitViewer();
// 采样按钮 // 显示视图
var sampleBtn = root.Q<Button>("SampleButton"); _viewMode = EViewMode.AssetView;
sampleBtn.clicked += SampleBtn_onClick; _viewModeMenu.text = EViewMode.AssetView.ToString();
_assetListViewer.AttachParent(root);
// 导出按钮 }
var exportBtn = root.Q<Button>("ExportButton"); private void SampleBtn_onClick()
exportBtn.clicked += ExportBtn_clicked; {
YooAssets.GetDebugReport(_debugReport);
// 用户列表菜单 _assetListViewer.FillViewData(_debugReport, _searchKeyWord);
_playerName = root.Q<Label>("PlayerName"); _bundleListViewer.FillViewData(_debugReport, _searchKeyWord);
_playerName.text = "Editor player"; }
private void OnSearchKeyWordChange(ChangeEvent<string> e)
// 视口模式菜单 {
_viewModeMenu = root.Q<ToolbarMenu>("ViewModeMenu"); _searchKeyWord = e.newValue;
_viewModeMenu.menu.AppendAction(EViewMode.AssetView.ToString(), OnViewModeMenuChange, OnViewModeMenuStatusUpdate, EViewMode.AssetView); _assetListViewer.FillViewData(_debugReport, _searchKeyWord);
_viewModeMenu.menu.AppendAction(EViewMode.BundleView.ToString(), OnViewModeMenuChange, OnViewModeMenuStatusUpdate, EViewMode.BundleView); _bundleListViewer.FillViewData(_debugReport, _searchKeyWord);
_viewModeMenu.text = EViewMode.AssetView.ToString(); }
private void ViewModeMenuAction1(DropdownMenuAction action)
// 搜索栏 {
var searchField = root.Q<ToolbarSearchField>("SearchField"); if (_viewMode != EViewMode.AssetView)
searchField.RegisterValueChangedCallback(OnSearchKeyWordChange); {
_viewMode = EViewMode.AssetView;
// 帧数相关 VisualElement root = this.rootVisualElement;
{ _viewModeMenu.text = EViewMode.AssetView.ToString();
_frameSlider = root.Q<SliderInt>("FrameSlider"); _assetListViewer.AttachParent(root);
_frameSlider.label = "Frame:"; _bundleListViewer.DetachParent();
_frameSlider.highValue = 0; }
_frameSlider.lowValue = 0; }
_frameSlider.value = 0; private void ViewModeMenuAction2(DropdownMenuAction action)
_frameSlider.RegisterValueChangedCallback(evt => {
{ if (_viewMode != EViewMode.BundleView)
OnFrameSliderChange(evt.newValue); {
}); _viewMode = EViewMode.BundleView;
VisualElement root = this.rootVisualElement;
var frameLast = root.Q<ToolbarButton>("FrameLast"); _viewModeMenu.text = EViewMode.BundleView.ToString();
frameLast.clicked += OnFrameLast_clicked; _assetListViewer.DetachParent();
_bundleListViewer.AttachParent(root);
var frameNext = root.Q<ToolbarButton>("FrameNext"); }
frameNext.clicked += OnFrameNext_clicked; }
private DropdownMenuAction.Status ViewModeMenuFun1(DropdownMenuAction action)
var frameClear = root.Q<ToolbarButton>("FrameClear"); {
frameClear.clicked += OnFrameClear_clicked; if (_viewMode == EViewMode.AssetView)
} return DropdownMenuAction.Status.Checked;
else
// 加载视图 return DropdownMenuAction.Status.Normal;
_assetListViewer = new DebuggerAssetListViewer(); }
_assetListViewer.InitViewer(); private DropdownMenuAction.Status ViewModeMenuFun2(DropdownMenuAction action)
{
// 加载视图 if (_viewMode == EViewMode.BundleView)
_bundleListViewer = new DebuggerBundleListViewer(); return DropdownMenuAction.Status.Checked;
_bundleListViewer.InitViewer(); else
return DropdownMenuAction.Status.Normal;
// 显示视图 }
_viewMode = EViewMode.AssetView; }
_assetListViewer.AttachParent(root);
// 远程调试
EditorConnection.instance.Initialize();
EditorConnection.instance.RegisterConnection(OnHandleConnectionEvent);
EditorConnection.instance.RegisterDisconnection(OnHandleDisconnectionEvent);
EditorConnection.instance.Register(RemoteDebuggerDefine.kMsgSendPlayerToEditor, OnHandlePlayerMessage);
RemoteDebuggerInRuntime.EditorHandleDebugReportCallback = OnHandleDebugReport;
}
catch (Exception e)
{
Debug.LogError(e.ToString());
}
}
public void OnDestroy()
{
// 远程调试
EditorConnection.instance.UnregisterConnection(OnHandleConnectionEvent);
EditorConnection.instance.UnregisterDisconnection(OnHandleDisconnectionEvent);
EditorConnection.instance.Unregister(RemoteDebuggerDefine.kMsgSendPlayerToEditor, OnHandlePlayerMessage);
_playerSessions.Clear();
}
private void OnHandleConnectionEvent(int playerId)
{
Debug.Log($"Game player connection : {playerId}");
_playerName.text = $"Connected player : {playerId}";
}
private void OnHandleDisconnectionEvent(int playerId)
{
Debug.Log($"Game player disconnection : {playerId}");
_playerName.text = $"Disconneced player : {playerId}";
}
private void OnHandlePlayerMessage(MessageEventArgs args)
{
var debugReport = DebugReport.Deserialize(args.data);
OnHandleDebugReport(args.playerId, debugReport);
}
private void OnHandleDebugReport(int playerId, DebugReport debugReport)
{
Debug.Log($"Handle player {playerId} debug report !");
_currentPlayerSession = GetOrCreatePlayerSession(playerId);
_currentPlayerSession.AddDebugReport(debugReport);
_frameSlider.highValue = _currentPlayerSession.MaxRangeValue;
_frameSlider.value = _currentPlayerSession.MaxRangeValue;
UpdateFrameView(_currentPlayerSession);
}
private void OnFrameSliderChange(int sliderValue)
{
if (_currentPlayerSession != null)
{
_rangeIndex = _currentPlayerSession.ClampRangeIndex(sliderValue); ;
UpdateFrameView(_currentPlayerSession, _rangeIndex);
}
}
private void OnFrameLast_clicked()
{
if (_currentPlayerSession != null)
{
_rangeIndex = _currentPlayerSession.ClampRangeIndex(_rangeIndex - 1);
_frameSlider.value = _rangeIndex;
UpdateFrameView(_currentPlayerSession, _rangeIndex);
}
}
private void OnFrameNext_clicked()
{
if (_currentPlayerSession != null)
{
_rangeIndex = _currentPlayerSession.ClampRangeIndex(_rangeIndex + 1);
_frameSlider.value = _rangeIndex;
UpdateFrameView(_currentPlayerSession, _rangeIndex);
}
}
private void OnFrameClear_clicked()
{
if (_currentPlayerSession != null)
{
_frameSlider.label = $"Frame:";
_frameSlider.value = 0;
_frameSlider.lowValue = 0;
_frameSlider.highValue = 0;
_currentPlayerSession.ClearDebugReport();
_assetListViewer.ClearView();
_bundleListViewer.ClearView();
}
}
private RemotePlayerSession GetOrCreatePlayerSession(int playerId)
{
if (_playerSessions.TryGetValue(playerId, out RemotePlayerSession session))
{
return session;
}
else
{
RemotePlayerSession newSession = new RemotePlayerSession(playerId);
_playerSessions.Add(playerId, newSession);
return newSession;
}
}
private void UpdateFrameView(RemotePlayerSession playerSession)
{
if (playerSession != null)
{
UpdateFrameView(playerSession, playerSession.MaxRangeValue);
}
}
private void UpdateFrameView(RemotePlayerSession playerSession, int rangeIndex)
{
if (playerSession == null)
return;
var debugReport = playerSession.GetDebugReport(rangeIndex);
if (debugReport != null)
{
_currentReport = debugReport;
_frameSlider.label = $"Frame: {debugReport.FrameCount}";
_assetListViewer.FillViewData(debugReport, _searchKeyWord);
_bundleListViewer.FillViewData(debugReport, _searchKeyWord);
}
}
private void SampleBtn_onClick()
{
// 发送采集数据的命令
RemoteCommand command = new RemoteCommand();
command.CommandType = (int)ERemoteCommand.SampleOnce;
command.CommandParam = string.Empty;
byte[] data = RemoteCommand.Serialize(command);
EditorConnection.instance.Send(RemoteDebuggerDefine.kMsgSendEditorToPlayer, data);
RemoteDebuggerInRuntime.EditorRequestDebugReport();
}
private void ExportBtn_clicked()
{
if (_currentReport == null)
{
Debug.LogWarning("Debug report is null.");
return;
}
string resultPath = EditorTools.OpenFolderPanel("Export JSON", "Assets/");
if (resultPath != null)
{
// 注意:排序保证生成配置的稳定性
foreach (var packageData in _currentReport.PackageDatas)
{
packageData.ProviderInfos.Sort();
foreach (var providerInfo in packageData.ProviderInfos)
{
providerInfo.DependBundleInfos.Sort();
}
}
string filePath = $"{resultPath}/{nameof(DebugReport)}_{_currentReport.FrameCount}.json";
string fileContent = JsonUtility.ToJson(_currentReport, true);
FileUtility.WriteAllText(filePath, fileContent);
}
}
private void OnSearchKeyWordChange(ChangeEvent<string> e)
{
_searchKeyWord = e.newValue;
if (_currentReport != null)
{
_assetListViewer.FillViewData(_currentReport, _searchKeyWord);
_bundleListViewer.FillViewData(_currentReport, _searchKeyWord);
}
}
private void OnViewModeMenuChange(DropdownMenuAction action)
{
var viewMode = (EViewMode)action.userData;
if (_viewMode != viewMode)
{
_viewMode = viewMode;
VisualElement root = this.rootVisualElement;
_viewModeMenu.text = viewMode.ToString();
if (viewMode == EViewMode.AssetView)
{
_assetListViewer.AttachParent(root);
_bundleListViewer.DetachParent();
}
else if (viewMode == EViewMode.BundleView)
{
_assetListViewer.DetachParent();
_bundleListViewer.AttachParent(root);
}
else
{
throw new NotImplementedException(viewMode.ToString());
}
}
}
private DropdownMenuAction.Status OnViewModeMenuStatusUpdate(DropdownMenuAction action)
{
var viewMode = (EViewMode)action.userData;
if (_viewMode == viewMode)
return DropdownMenuAction.Status.Checked;
else
return DropdownMenuAction.Status.Normal;
}
}
} }
#endif #endif

View File

@ -1,15 +1,7 @@
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../UIElementsSchema/UIElements.xsd" editor-extension-mode="True"> <ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../UIElementsSchema/UIElements.xsd" editor-extension-mode="True">
<uie:Toolbar name="TopToolbar" style="display: flex;"> <uie:Toolbar name="Toolbar" style="display: flex;">
<ui:Label text="Player" display-tooltip-when-elided="true" name="PlayerName" style="width: 200px; -unity-text-align: middle-left; padding-left: 5px;" /> <uie:ToolbarButton text="刷新" display-tooltip-when-elided="true" name="SampleButton" style="width: 70px; background-color: rgb(15, 118, 31); -unity-text-align: middle-center; border-top-left-radius: 2px; border-bottom-left-radius: 2px; border-top-right-radius: 2px; border-bottom-right-radius: 2px; border-left-width: 1px; border-right-width: 1px;" />
<uie:ToolbarMenu display-tooltip-when-elided="true" name="ViewModeMenu" text="ViewMode" style="width: 100px; flex-grow: 0;" /> <uie:ToolbarMenu display-tooltip-when-elided="true" name="ViewModeMenu" text="ViewMode" style="width: 100px; flex-grow: 0;" />
<uie:ToolbarSearchField focusable="true" name="SearchField" style="flex-grow: 1;" /> <uie:ToolbarSearchField focusable="true" name="SearchField" style="flex-grow: 1;" />
<uie:ToolbarButton text="刷新" display-tooltip-when-elided="true" name="SampleButton" style="width: 70px; background-color: rgb(15, 118, 31); -unity-text-align: middle-center; border-top-left-radius: 2px; border-bottom-left-radius: 2px; border-top-right-radius: 2px; border-bottom-right-radius: 2px; border-left-width: 1px; border-right-width: 1px;" />
<uie:ToolbarButton text="导出" display-tooltip-when-elided="true" name="ExportButton" style="width: 70px; background-color: rgb(15, 118, 31); -unity-text-align: middle-center; border-top-left-radius: 2px; border-bottom-left-radius: 2px; border-top-right-radius: 2px; border-bottom-right-radius: 2px; border-left-width: 1px; border-right-width: 1px;" />
</uie:Toolbar>
<uie:Toolbar name="FrameToolbar">
<ui:SliderInt picking-mode="Ignore" label="Frame:" value="42" high-value="100" name="FrameSlider" style="flex-grow: 1;" />
<uie:ToolbarButton text=" &lt;&lt; " display-tooltip-when-elided="true" name="FrameLast" />
<uie:ToolbarButton text=" &gt;&gt; " display-tooltip-when-elided="true" name="FrameNext" />
<uie:ToolbarButton text="Clear" display-tooltip-when-elided="true" name="FrameClear" />
</uie:Toolbar> </uie:Toolbar>
</ui:UXML> </ui:UXML>

Some files were not shown because too many files have changed in this diff Show More