Files
plugin-library/Assets/00.StaryEvo/Editor/ArtBuild/BuildArtAssetWindow.cs

516 lines
20 KiB
C#
Raw Normal View History

2025-10-24 11:11:59 +08:00
/****************************************************
BuildAssetWindow.cs
xosmo_
2025/3/10 10:43:20
*****************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor;
using UnityEditor;
using UnityEngine;
using YooAsset;
using YooAsset.Editor;
namespace Stary.Evo.Editor
{
2025-10-24 11:50:03 +08:00
public class BuildArtAssetWindow : OdinEditorWindow
2025-10-24 11:11:59 +08:00
{
public static OdinEditorWindow window;
private HotfixMainResDomain hotfixMainResDomain;
2025-10-24 19:08:10 +08:00
[MenuItem("Evo/Art/Art资源打包工具",false, 1)]
2025-10-24 11:11:59 +08:00
static void ShowWindows()
{
if (CreatAssetWindow.GetCreatDomainAll().Count <= 0)
{
2025-10-24 11:50:03 +08:00
EditorUtility.DisplayDialog("提示", "不存在Art元素无法打开此面板请先创建Art元素", "确定");
2025-10-24 11:11:59 +08:00
return;
}
2025-10-24 11:50:03 +08:00
window = (BuildArtAssetWindow)EditorWindow.GetWindow(typeof(BuildArtAssetWindow));
2025-10-24 11:11:59 +08:00
window.Show();
}
protected override void OnDisable()
{
base.OnDisable();
EditorUtility.ClearProgressBar();
}
protected override async void Initialize()
{
base.Initialize();
GetBuildPackageNames();
//初始化读取资源配置表
hotfixMainResDomain = Resources.Load<HotfixMainResDomain>("HotfixMainResDomain");
if (hotfixMainResDomain == null)
{
Debug.LogError($"UnityEvo:读取资源配置表失败【HotfixMainResDomain】...表在Resources下不存在请创建");
}
else
{
ip = hotfixMainResDomain.hotfixMainResDomainEntity.ipconfig;
2025-10-24 11:50:03 +08:00
EditorPrefs.SetString("ip", ip);
2025-10-24 11:11:59 +08:00
userName = hotfixMainResDomain.hotfixMainResDomainEntity.username;
password = hotfixMainResDomain.hotfixMainResDomainEntity.password;
}
if (string.IsNullOrEmpty(ip))
{
buildAssetType = BuildAssetType.Login;
return;
}
bool isValidateToken = await WebRequestSystem.GetValidateToken(ip + "/Authentication/validateToken");
if (isValidateToken)
{
buildAssetType = BuildAssetType.Build;
2025-10-24 11:50:03 +08:00
}
else
{
buildAssetType = BuildAssetType.Login;
2025-10-24 11:11:59 +08:00
}
2025-10-24 11:50:03 +08:00
//初始化打包管线
_buildPipelineViewer = new ScriptableBuildPipelineViewer(packageName,
EBuildPipeline.ScriptableBuildPipeline.ToString(), packageVersion);
_buildPipelineViewer.clearBuildCacheToggle = true;
_buildPipelineViewer.useAssetDependencyDBToggle = false;
_buildPipelineViewer.SetBuildCacheToggle();
_buildPipelineViewer.SetUseAssetDependencyDB();
2025-10-24 11:11:59 +08:00
}
public static void RemoveBuildAssetWindow()
{
if (window != null)
window.Close();
}
[EnumToggleButtons, HideLabel] public BuildAssetType buildAssetType;
#region BuildAssetLogin
[ShowIf("@ buildAssetType== BuildAssetType.Login")]
[BoxGroup("Login", showLabel: false)]
[OnValueChanged("SetWebRequestInfo")]
public string ip, userName, password;
[ShowIf("@ buildAssetType== BuildAssetType.Login")]
[BoxGroup("Login", showLabel: false)]
[Button("登录", ButtonSizes.Large)]
[InfoBox("@ message", InfoMessageType.Info)]
public async void LoginButton()
{
string url = ip + "/Authentication/login";
EditorUtility.DisplayProgressBar("提示", $"登陆中~", 0f);
bool islogin = await WebRequestSystem.Login(url, userName, password);
float progress = 0f;
while (progress >= 1f)
{
progress += 0.1f;
EditorUtility.DisplayProgressBar("提示", $"登陆中~", progress);
await Task.Delay(TimeSpan.FromSeconds(0.2f));
}
EditorUtility.ClearProgressBar();
UpdateMessage(islogin);
}
private void SetWebRequestInfo()
{
if (hotfixMainResDomain != null)
{
hotfixMainResDomain.hotfixMainResDomainEntity.ipconfig = ip;
hotfixMainResDomain.hotfixMainResDomainEntity.username = userName;
hotfixMainResDomain.hotfixMainResDomainEntity.password = password;
2025-10-24 11:50:03 +08:00
EditorPrefs.SetString("ip", ip);
2025-10-24 11:11:59 +08:00
EditorUtility.SetDirty(hotfixMainResDomain);
AssetDatabase.SaveAssets();
}
}
private string message;
public void UpdateMessage(bool islogin)
{
message = "当前登录状态为:" + islogin;
if (islogin)
{
buildAssetType = BuildAssetType.Build;
}
}
#endregion
protected void OnSelectionChange()
{
2025-10-24 11:50:03 +08:00
// EditorUtility.SetDirty(BuildAssetDataSetting);
// AssetDatabase.SaveAssets();
2025-10-24 11:11:59 +08:00
//AssetDatabase.Refresh();
}
[BoxGroup("Build", showLabel: false)]
[ShowIf("@ buildAssetType== BuildAssetType.Build")]
[Title("包裹列表", titleAlignment: TitleAlignments.Centered)]
[HorizontalGroup("Build/BuildPipeline"), HideLabel]
[ValueDropdown("GetBuildPackageNames")]
[OnValueChanged("SetBuildPackageNames")]
public string selectedPackageNames;
[BoxGroup("Build", showLabel: false)]
[ShowIf("@ buildAssetType== BuildAssetType.Build")]
[Title("当前打包平台", titleAlignment: TitleAlignments.Centered)]
[ReadOnly]
[HorizontalGroup("Build/BuildPipeline"), HideLabel]
public string buildTarget;
2025-10-24 11:50:03 +08:00
private static string packageName;
2025-10-24 11:11:59 +08:00
2025-10-24 11:50:03 +08:00
[Title("版本号", titleAlignment: TitleAlignments.Centered)]
[HorizontalGroup("Build/PackageVersion"), HideLabel]
[ShowIf("@ buildAssetType== BuildAssetType.Build")]
[OnValueChanged("OnPackageValueChanged")]
public string packageVersion;
2025-10-24 11:11:59 +08:00
2025-10-24 11:50:03 +08:00
private AbstractBuildPipelineViewer _buildPipelineViewer;
2025-10-24 11:11:59 +08:00
#region BuildAsset
2025-10-24 11:50:03 +08:00
public void OnPackageValueChanged()
{
_buildPipelineViewer.SetBuildPackageData(packageName, EBuildPipeline.ScriptableBuildPipeline.ToString(),
packageVersion);
}
2025-10-24 11:11:59 +08:00
/// <summary>
/// 检测当前所有包裹
/// </summary>
/// <returns></returns>
private List<string> GetBuildPackageNames()
{
List<string> result = new List<string>();
2025-10-24 11:50:03 +08:00
foreach (var name in CreatArtAssetWindow.GetCreatDomainAllName())
2025-10-24 11:11:59 +08:00
{
result.Add(name);
}
if (selectedPackageNames.IsNullOrEmpty())
{
selectedPackageNames = result[0];
}
SetBuildPackageNames();
return result;
}
2025-10-24 11:50:03 +08:00
/// <summary>
/// 获取当前包裹
/// </summary>
/// <returns></returns>
public static string GetBuildPackageName()
{
return packageName;
}
2025-10-24 11:11:59 +08:00
/// <summary>
/// 设置当前包裹
/// </summary>
/// <returns></returns>
private void SetBuildPackageNames()
{
if (selectedPackageNames != packageName)
{
2025-10-24 11:50:03 +08:00
GetHostBuildPackageVersion();
Init();
2025-10-24 11:11:59 +08:00
}
packageName = selectedPackageNames;
2025-10-24 11:50:03 +08:00
OnPackageValueChanged();
2025-10-24 11:11:59 +08:00
}
#endregion
#region Update
[BoxGroup("Build", showLabel: false)]
[ShowIf("@ buildAssetType== BuildAssetType.Build")]
[Title("打包本地资源", titleAlignment: TitleAlignments.Centered)]
[HideLabel]
public BuildAssetEntity onBuildPipelineEntity;
[BoxGroup("Build", showLabel: false)]
2025-10-24 11:50:03 +08:00
[ShowIf("@ buildAssetType== BuildAssetType.Build")]
2025-10-24 11:11:59 +08:00
[Title("上传资源", titleAlignment: TitleAlignments.Centered)]
[HideLabel]
public BuildAssetEntity onUpdateBuildPipelineEntity;
private void OnBuildPipeline()
{
if (EditorUtility.DisplayDialog("提示", $"开始构建资源包[{selectedPackageNames}]", "Yes", "No"))
{
EditorTools.ClearUnityConsole();
2025-10-24 11:50:03 +08:00
MarkAdressable.AddArtMark(() => { EditorApplication.delayCall += _buildPipelineViewer.ExecuteBuild; });
2025-10-24 11:11:59 +08:00
}
else
{
Debug.LogWarning("[Build] 打包已经取消");
}
}
private async void OnUpdateBuildPipeline()
{
if (EditorUtility.DisplayDialog("提示", $"开始上传至服务器[{selectedPackageNames}]", "Yes", "No"))
{
// 新增打包为zip的逻辑
2025-10-24 11:50:03 +08:00
string zipFilePath = BuildZip();
await UpdateFileDataResDomain(zipFilePath);
2025-10-24 11:11:59 +08:00
await Task.Delay(1000);
EditorUtility.ClearProgressBar();
}
else
{
EditorUtility.ClearProgressBar();
EditorUtility.DisplayDialog("提示", "Update] 上传已经取消", "确定");
Debug.LogWarning("[Update] 上传已经取消");
}
}
2025-10-24 11:50:03 +08:00
public string BuildZip()
2025-10-24 11:11:59 +08:00
{
2025-10-24 11:50:03 +08:00
EditorUtility.DisplayProgressBar("提示", $"开始上传{packageName}(打包zip)", 0.0f);
2025-10-24 11:11:59 +08:00
// 新增打包为zip的逻辑
string zipFileName =
2025-10-24 11:50:03 +08:00
$"{packageName}_{packageVersion}.zip";
2025-10-24 11:11:59 +08:00
//原yooAsset目录
var outputPackageDirectory =
2025-10-24 11:50:03 +08:00
$"{AssetBundleBuilderHelper.GetDefaultBuildOutputRoot()}/{EditorUserBuildSettings.activeBuildTarget}/{packageName}";
2025-10-24 11:11:59 +08:00
//拷贝目录
2025-10-24 11:50:03 +08:00
string outFilePath = $"{outputPackageDirectory}/{packageVersion}";
2025-10-24 11:11:59 +08:00
var copyPackageDirectory =
2025-10-24 11:50:03 +08:00
$"{Application.streamingAssetsPath}/{YooAssetSettingsData.GetDefaultYooFolderName()}/{packageName}";
2025-10-24 11:11:59 +08:00
//拷贝BuildinCatalog文件
CreateBuildinCatalogFile("BuildinCatalog.json", copyPackageDirectory, outFilePath);
CreateBuildinCatalogFile("BuildinCatalog.bytes", copyPackageDirectory, outFilePath);
//输出目录
string zipFilePath = Path.Combine(outputPackageDirectory, zipFileName);
try
{
using (FileStream zipStream = new FileStream(zipFilePath, FileMode.Create))
using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create))
{
// 指定需要压缩的后缀(例如:只压缩.json和.dll文件
//string[] targetExtensions = { ".bundle" };
// 遍历目录下所有文件
// foreach (string filePath in Directory.GetFiles(outFilePath, "*.*", SearchOption.AllDirectories)
// .Where(f => targetExtensions.Contains(Path.GetExtension(f),
// StringComparer.OrdinalIgnoreCase)))
foreach (string filePath in Directory.GetFiles(outFilePath, "*.*", SearchOption.AllDirectories))
{
// 获取文件在压缩包中的相对路径
string entryName = Path.GetRelativePath(outFilePath, filePath);
// 创建zip条目
ZipArchiveEntry entry = archive.CreateEntry(entryName,
System.IO.Compression.CompressionLevel.Optimal);
// 写入文件内容
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (Stream entryStream = entry.Open())
{
fileStream.CopyTo(entryStream);
}
}
}
Debug.Log($"成功打包为zip{zipFilePath}");
2025-10-24 11:50:03 +08:00
EditorUtility.DisplayProgressBar("提示", $"开始上传{packageName}(打包zip)", 0.25f);
2025-10-24 11:11:59 +08:00
return zipFilePath;
}
catch (Exception ex)
{
Debug.LogError($"打包zip失败{ex.Message}");
EditorUtility.ClearProgressBar();
return default;
}
}
private static void CreateBuildinCatalogFile(string fileName, string copyPackageDirectory, string outFilePath)
{
// 假设 BuildinCatalog 文件名为 BuildinCatalog.json
string sourcePath = Path.Combine(copyPackageDirectory, fileName); // 源文件路径
2025-10-24 11:50:03 +08:00
string destinationPath = Path.Combine(outFilePath, fileName); // 目标文件路径
2025-10-24 11:11:59 +08:00
// 如果目标文件已存在,则覆盖
if (File.Exists(destinationPath))
{
File.Delete(destinationPath);
}
// 执行拷贝操作
File.Copy(sourcePath, destinationPath);
}
2025-10-24 11:50:03 +08:00
public async Task UpdateFileDataResDomain(string zipFilePath)
2025-10-24 11:11:59 +08:00
{
//初始化读取资源配置表
HotfixMainResDomain hotfixMainResDomain = Resources.Load<HotfixMainResDomain>("HotfixMainResDomain");
if (hotfixMainResDomain == null)
{
Debug.LogError($"UnityEvo:读取资源配置表失败【HotfixMainResDomain】...表不存在");
return;
}
var ip = hotfixMainResDomain.hotfixMainResDomainEntity.ipconfig;
var messageEntity = await WebRequestSystem.PostFile(ip + "/FileLoad/UpLoadFile", new[] { zipFilePath });
2025-10-24 11:50:03 +08:00
EditorUtility.DisplayProgressBar("提示", $"开始上传{packageName}(上传zip文件)", 0.5f);
2025-10-24 11:11:59 +08:00
if (messageEntity.code == 200)
{
List<ResultMessageEntity> resultMessageEntities =
JsonConvert.DeserializeObject<List<ResultMessageEntity>>(messageEntity.data.ToString());
if (resultMessageEntities.Count > 0)
{
EditorUtility.DisplayProgressBar("提示", "开始上传(更新数据库)", 0.75f);
foreach (var resultMessageEntity in resultMessageEntities)
{
var data = JsonConvert.DeserializeObject(resultMessageEntity.data.ToString()) as JObject;
string fileId = data["id"].ToString();
ResDmainAddRequst resDmainAddRequst = new ResDmainAddRequst()
{
ProductName = Application.identifier,
2025-10-24 11:50:03 +08:00
DomainName = packageName,
2025-10-24 11:11:59 +08:00
Platform = EditorUserBuildSettings.activeBuildTarget.ToString(),
2025-10-24 11:50:03 +08:00
PackageVersion = packageVersion,
2025-10-24 11:11:59 +08:00
DocumentFileId = fileId
};
var resResultMessage = await WebRequestSystem.Post(ip + "/ResDomain/AddResDomain",
JsonConvert.SerializeObject(resDmainAddRequst));
//如果低于服务器版本,更新版本号
if (resResultMessage.code == 1009)
{
ResDmainVersionResponse dmainVersionResponse =
JsonConvert.DeserializeObject<ResDmainVersionResponse>(resResultMessage.data
.ToString());
2025-10-24 11:50:03 +08:00
bool isEndWithDigit =
System.Text.RegularExpressions.Regex.IsMatch(dmainVersionResponse.PackageVersion,
@"\d$");
if (isEndWithDigit)
{
// 提取版本号结尾的数字部分
string versionEndDigits = System.Text.RegularExpressions.Regex
.Match(dmainVersionResponse.PackageVersion, @"(\d+)$").Groups[1].Value;
int versionEndDigit = int.Parse(versionEndDigits) + 1;
// 或者移除版本号结尾的数字
string versionWithoutEndDigits =
System.Text.RegularExpressions.Regex.Replace(dmainVersionResponse.PackageVersion,
@"\d+$", "");
packageVersion = versionWithoutEndDigits + versionEndDigit;
}
2025-10-24 11:11:59 +08:00
EditorUtility.DisplayDialog("提示",
2025-10-24 11:50:03 +08:00
$"{resResultMessage.message + $"\n{resResultMessage.data.ToString()},{packageVersion}"}",
"确定");
2025-10-24 11:11:59 +08:00
}
}
2025-10-24 11:50:03 +08:00
EditorUtility.DisplayProgressBar("提示", $"开始上传{packageName}(更新数据库)", 1f);
2025-10-24 11:11:59 +08:00
}
}
else
{
EditorUtility.DisplayProgressBar("提示", $"{messageEntity.message}", 1f);
}
await Task.Delay(1000);
EditorUtility.ClearProgressBar();
return;
}
/// <summary>
/// 获取服务器上版本号
/// </summary>
2025-10-24 11:50:03 +08:00
private async void GetHostBuildPackageVersion()
2025-10-24 11:11:59 +08:00
{
var resDmainAddRequst = new ResDmainRequst()
{
ProductName = Application.identifier,
DomainName = selectedPackageNames,
Platform = EditorUserBuildSettings.activeBuildTarget.ToString(),
};
var resResultMessage = await WebRequestSystem.Post(ip + "/ResDomain/GetResDomainByDomain",
JsonConvert.SerializeObject(resDmainAddRequst));
//如果低于服务器版本,更新版本号
if (resResultMessage.code != 1011)
{
if (resResultMessage.data != null)
{
ResDmainResponse domainResponse =
JsonConvert.DeserializeObject<ResDmainResponse>(resResultMessage.data
.ToString());
2025-10-24 11:50:03 +08:00
packageVersion = domainResponse.PackageVersion;
2025-10-24 11:11:59 +08:00
}
else
{
Debug.LogError($"UnityEvo获取服务器版本失败,resResultMessage.data为空");
}
}
else
{
EditorUtility.DisplayDialog("提示",
2025-10-24 11:50:03 +08:00
$"{resResultMessage.message},默认test_1.0版本 ", "确定");
packageVersion = "test_1.0";
2025-10-24 11:11:59 +08:00
}
}
#endregion
protected void Init()
{
//Update
buildTarget = EditorUserBuildSettings.activeBuildTarget.ToString();
onBuildPipelineEntity =
2025-10-24 11:50:03 +08:00
new BuildAssetEntity("打包", $"打包资源包【版本:{packageVersion}】", OnBuildPipeline);
2025-10-24 11:11:59 +08:00
onUpdateBuildPipelineEntity =
2025-10-24 11:50:03 +08:00
new BuildAssetEntity("更新", $"更新至服务器【版本:{packageVersion}】",
2025-10-24 11:11:59 +08:00
OnUpdateBuildPipeline);
}
private Vector2 scroll;
protected override void DrawEditor(int index)
{
scroll = GUILayout.BeginScrollView(scroll);
{
base.DrawEditor(index);
}
GUILayout.EndScrollView();
UpdateBuildPipelineButtonName();
}
public void UpdateBuildPipelineButtonName()
{
2025-10-24 11:50:03 +08:00
onBuildPipelineEntity.SetButtonName($"打包资源包【版本:{packageVersion}】");
onUpdateBuildPipelineEntity.SetButtonName($"更新至服务器【版本:{packageVersion}】");
2025-10-24 11:11:59 +08:00
}
}
}