Compare commits

...

150 Commits

Author SHA1 Message Date
hevinci
954e76ab33 Update CHANGELOG.md 2023-01-03 10:06:51 +08:00
hevinci
82bda518c9 Update package.json 2023-01-03 10:06:41 +08:00
hevinci
cdc5bcd31f fix #56
修复更新资源清单错误计算超时时间的问题。
2022-12-29 14:23:16 +08:00
hevinci
61f6d480ae Update runtime code
修复清单解析异步操作的进度条变化
2022-12-28 16:44:25 +08:00
hevinci
df6df3548c Update document 2022-12-27 10:20:13 +08:00
hevinci
ac839450e2 update runtime code 2022-12-27 10:19:35 +08:00
hevinci
4fa01e1a29 update editor code 2022-12-27 10:18:57 +08:00
hevinci
db2a45ec35 Update CHANGELOG.md 2022-12-26 01:21:07 +08:00
hevinci
76c6f5cc1c Update package.json 2022-12-26 01:20:48 +08:00
hevinci
339b519881 update editor code 2022-12-26 01:04:43 +08:00
hevinci
de2fab1370 update runtime code 2022-12-26 01:04:35 +08:00
hevinci
fd4b6794cc update samples 2022-12-26 00:49:40 +08:00
hevinci
f3e3f7cf85 update runtime code 2022-12-26 00:48:56 +08:00
hevinci
dd824254a9 update runtime code 2022-12-25 00:25:41 +08:00
hevinci
16943d4590 update runtime code 2022-12-24 22:09:14 +08:00
hevinci
a95697088b update editor code 2022-12-24 22:03:29 +08:00
hevinci
f771a98f25 update editor code
修复开启UniqueBundleName选项后,SBP构建报错的问题。
2022-12-21 17:11:09 +08:00
hevinci
3b1a8beadf update runtime code 2022-12-21 17:10:28 +08:00
hevinci
209e9d7705 update samples 2022-12-21 12:06:07 +08:00
hevinci
de09a042e6 update runtime code 2022-12-21 12:05:05 +08:00
hevinci
66cd491493 update editor code 2022-12-21 12:04:56 +08:00
hevinci
4a158319e5 update runtime code 2022-12-21 10:54:22 +08:00
hevinci
b322a848ba update samples 2022-12-20 16:17:16 +08:00
hevinci
4e759134bd update runtime code 2022-12-20 16:17:01 +08:00
hevinci
5c16171781 update runtime code 2022-12-18 21:55:49 +08:00
hevinci
08ad68d4a2 update samples 2022-12-17 22:38:26 +08:00
hevinci
2ace30acd8 update runtime code 2022-12-17 22:37:39 +08:00
hevinci
fc55b1be82 update runtime code 2022-12-17 18:13:08 +08:00
hevinci
b287dfedcf update samples 2022-12-17 18:08:49 +08:00
hevinci
d6984f0ad4 update editor code 2022-12-17 18:08:38 +08:00
hevinci
85cb1ed3f6 update runtime code
优化清单分帧加载方式。
2022-12-17 18:08:23 +08:00
hevinci
32b5240fcc update patch system
缓存文件验证采取分帧处理。
2022-12-14 21:53:09 +08:00
hevinci
7b9fda2298 update download system
优化资源文件下载流程。
2022-12-13 23:30:16 +08:00
hevinci
15a605b677 update UniTask sample 2022-12-13 12:22:27 +08:00
hevinci
f4a3fcece8 Fixed #54 2022-12-13 11:46:39 +08:00
hevinci
d67fc31c26 update patch system
初始化的时候检测覆盖安装
2022-12-13 11:29:22 +08:00
hevinci
889000d8a8 update samples 2022-12-12 20:16:34 +08:00
hevinci
e827e74cc7 update runtime code 2022-12-07 19:10:13 +08:00
hevinci
45ca1ebf02 update runtime logic
优化字符串拼接方法。
2022-12-07 17:52:32 +08:00
hevinci
3a81d7babd update editor logic 2022-12-07 17:52:02 +08:00
hevinci
a1d5949177 Update document 2022-12-07 15:10:30 +08:00
hevinci
d7ae52160b update runtime logic
优化了补丁清单解析。
2022-12-07 11:26:08 +08:00
hevinci
e3fa33b9b5 update editor logic
移除BundleName_HashName选项。
2022-12-07 11:25:41 +08:00
hevinci
ac251114ff update samples 2022-12-05 16:30:47 +08:00
hevinci
824d1c1501 update asset system 2022-12-05 16:29:45 +08:00
hevinci
ac88fd5cf6 update asset sytem
资源句柄类增加GetDownloadReport()方法。
2022-12-05 14:36:26 +08:00
hevinci
5197d42807 Update CHANGELOG.md 2022-12-04 20:27:27 +08:00
hevinci
7a0f4caa9b Update package.json 2022-12-04 20:27:13 +08:00
hevinci
5bf1d29edc update utility 2022-12-04 20:14:02 +08:00
hevinci
2687466ed4 Update editor file 2022-12-03 23:16:39 +08:00
hevinci
14512d6470 Update samples 2022-12-03 23:16:16 +08:00
hevinci
32268f5a4a Update editor logic
资源收集界面规则选项显示别名
2022-12-03 23:16:04 +08:00
何冠峰
81401ca0b8 Merge pull request #53 from ZensYue/main
[add]Add ShowEditorAlias 添加显示编辑器名字
2022-12-03 20:12:31 +08:00
hevinci
688cc271d5 Update runtime logic
UpdatePackageVersionAsync()方法增加appendTimeTicks参数
2022-12-03 20:03:10 +08:00
hevinci
a290353cfa Update runtime logic
在初始化失败的时候,销毁YooAssets会报异常。
2022-12-03 19:48:17 +08:00
hevinci
6038e7acd6 Update asset system 2022-12-03 19:13:11 +08:00
何冠峰
4abec5a389 Merge pull request #52 from gaozhou/main
为handle 添加 using 支持
2022-12-03 19:00:44 +08:00
hevinci
a2b51a8044 Update samples 2022-12-03 18:49:05 +08:00
hevinci
19cb239746 Update logic code
优化补丁清单格式为二进制。
2022-12-03 18:48:51 +08:00
hevinci
7aab610be5 Add binary buffer class 2022-12-03 18:42:28 +08:00
hevinci
4ec5a126ac Remove BitMask files 2022-12-03 18:07:52 +08:00
zensyue
32643caf51 Merge pull request #1 from ZensYue/dev
Dev
2022-12-02 20:46:13 +08:00
ZensYue
114ebab6ae [bugfix]Convert the show name to the type name 把显示名字转换成类型名字 2022-12-02 20:39:28 +08:00
gaozhou
d1463e1fc6 为handle 添加 using 支持 2022-12-02 14:23:58 +08:00
ZensYue
aa49980231 [add]Add ShowEditorAlias 添加显示编辑器名字 2022-12-02 12:31:15 +08:00
hevinci
2696da092d update samples 2022-11-29 11:07:38 +08:00
hevinci
5415d95f36 Fix #46
修复资源包初始化失败之后,再次初始化提示异常的问题。
2022-11-29 11:06:24 +08:00
hevinci
efa71c8bb7 Update FAQ.md 2022-11-28 22:24:36 +08:00
hevinci
d59df4c561 update document 2022-11-27 15:40:09 +08:00
hevinci
140bcb037f Update CHANGELOG.md 2022-11-26 18:17:22 +08:00
hevinci
2a4384e093 Update package.json 2022-11-26 18:17:20 +08:00
hevinci
5aafed85ed Update CHANGELOG.md 2022-11-26 18:11:34 +08:00
hevinci
6ad4b91c60 Update package.json 2022-11-26 18:11:20 +08:00
hevinci
cd62686316 update editor code
非原生文件收集器自动移除Unity无法识别的文件。
2022-11-26 17:54:42 +08:00
hevinci
dcd606e573 update samples 2022-11-26 17:41:34 +08:00
hevinci
f6f326119c update samples 2022-11-26 17:39:52 +08:00
hevinci
f31e5e0d22 update runtime code 2022-11-26 17:39:35 +08:00
hevinci
abc12d2a1d Update runtime code
增加资源系统销毁方法。
2022-11-26 16:43:05 +08:00
hevinci
b7e2f084b1 Update editor code 2022-11-26 15:31:46 +08:00
hevinci
adf1776b1e Update runtime code
优化调试信息的加载状态显示为文本。
2022-11-26 15:31:35 +08:00
hevinci
fd1edcdedf Fix #45 2022-11-26 15:14:46 +08:00
hevinci
ebc25c401d update sample 2022-11-26 15:09:12 +08:00
hevinci
67574bf759 update samples 2022-11-26 11:29:53 +08:00
hevinci
e94923c3c6 Update AssetSystem 2022-11-26 11:29:39 +08:00
hevinci
5718d57b88 update sample 2022-11-25 21:40:54 +08:00
hevinci
82cff36194 Update samples 2022-11-23 16:46:25 +08:00
hevinci
3e4e2d5eb6 Update space shooter 2022-11-23 12:35:27 +08:00
hevinci
015f09d27b Update runtime code 2022-11-23 12:33:12 +08:00
hevinci
3fedc5b1b3 Update AssetBundleCollector
原生文件打包规则包含文件后缀名
2022-11-21 19:07:34 +08:00
hevinci
4776ab9bd8 Update document 2022-11-21 09:52:18 +08:00
hevinci
3bb01ef9a8 Update CHANGELOG.md 2022-11-19 18:34:43 +08:00
hevinci
0204f5f68f Update package.json 2022-11-19 18:34:39 +08:00
hevinci
217d88beaa Update basic sample 2022-11-19 18:34:31 +08:00
hevinci
77080b3934 Update basic sample 2022-11-19 17:54:41 +08:00
hevinci
83f6dc2f76 Update editor code 2022-11-19 17:54:18 +08:00
hevinci
29b3ca4e69 Update runtime code
重构原生文件加载流程。
2022-11-19 17:54:09 +08:00
hevinci
9394ff49fd Update basic sample 2022-11-18 21:35:42 +08:00
hevinci
49949ecda5 Update runtime code
优化资源包缓存文件清理方式。
2022-11-18 21:33:58 +08:00
hevinci
1dab0f2b19 Update patch system
下载器增加取消方法。
2022-11-18 16:45:56 +08:00
hevinci
1cf03bf049 Update basic sample 2022-11-18 10:21:48 +08:00
何冠峰
c00594738f Update asset system
支持场景文件跨资源包配置。
2022-11-16 16:25:43 +08:00
何冠峰
d5f601b0eb Update runtime code 2022-11-16 14:49:38 +08:00
何冠峰
304bff1f19 Fix #43
修复了打包规则按收集器路径来命名,bundle文件名称显示不正确。
2022-11-16 11:51:01 +08:00
hevinci
ce9e0cd88c Update README.md 2022-11-11 11:02:56 +08:00
hevinci
40903d9ad5 Update runtime code 2022-11-11 11:01:37 +08:00
hevinci
0fc97ad2f1 Update document 2022-11-11 11:01:25 +08:00
hevinci
2bb66ea583 Update README.md 2022-11-11 11:01:11 +08:00
hevinci
03aa9780eb Update CHANGELOG.md 2022-11-04 13:38:26 +08:00
hevinci
d3a9005964 Update package.json 2022-11-04 13:38:22 +08:00
hevinci
48bcf4a848 Update document 2022-11-04 13:22:31 +08:00
hevinci
72f0426531 Update PatchSystem
移除了WeaklyUpdatePatchManifestAsync()方法
新增了CheckPackageContentsAsync()方法
2022-11-04 13:10:08 +08:00
hevinci
44ec5b3de3 Update document 2022-11-04 11:39:16 +08:00
hevinci
292fdb1288 Update document 2022-11-03 20:47:40 +08:00
hevinci
76e65286fd Update basic sample 2022-11-03 20:18:05 +08:00
hevinci
9397a0ebae Update ShaderVariantCollector 2022-11-03 20:17:07 +08:00
hevinci
c37b5e52ac Update basic sample 2022-11-03 15:21:03 +08:00
hevinci
ecfced7195 Fix #38 2022-11-03 12:02:10 +08:00
hevinci
1c7a79f7d7 Fix #37 2022-11-03 11:51:17 +08:00
hevinci
1149906786 Fix #29 2022-11-03 11:38:26 +08:00
hevinci
9db111c08a Update runtime code 2022-11-03 10:37:34 +08:00
hevinci
0844447b46 Update AssetBundleBuilder
界面增加构建版本选项
2022-11-03 10:15:27 +08:00
hevinci
c7116ad165 Update basic sample 2022-11-02 22:04:11 +08:00
hevinci
a805e0639e Update editor code 2022-11-02 21:57:08 +08:00
hevinci
e8e69a2e86 Update runtime code
重写了文件解密流程。
2022-11-02 21:54:44 +08:00
hevinci
3e4761a60f Update basic sample 2022-11-01 23:13:45 +08:00
hevinci
3413157c67 Update editor code
调整加密文件的生成规则
2022-11-01 23:13:18 +08:00
hevinci
b5f2174ed0 Update runtime code 2022-11-01 23:02:20 +08:00
hevinci
bdc8285255 Update basic sample 2022-10-31 16:46:05 +08:00
hevinci
cd79f0e434 Update runtime code
AssetsPackage.WeaklyUpdateManifestAsync(string packageVersion)移除了packageVersion参数。
优化了HostPlayMode的初始化逻辑,优先读取沙盒内的清单,如果不存在则读取内置清单。
2022-10-31 16:45:21 +08:00
hevinci
171f40551e Update document 2022-10-28 10:46:35 +08:00
hevinci
ba4efebbce Update CHANGELOG.md 2022-10-27 19:01:07 +08:00
hevinci
2486287a0e Update package.json 2022-10-27 19:01:04 +08:00
hevinci
2599639aeb Update PatchSystem 2022-10-27 14:20:05 +08:00
hevinci
c1192b37c6 Update Extension Sample 2022-10-26 21:03:19 +08:00
hevinci
1f647163f2 Update Basic Sample 2022-10-26 21:03:10 +08:00
hevinci
cc04efe76b Update runtime code
UpdateStaticVersionOperation.PackageCRC重名为PackageVersion。
AssetPackage.GetHumanReadableVersion()重名为GetPackageVersion()
2022-10-26 21:02:25 +08:00
hevinci
18426d0481 Update AssetBundleBuilder 2022-10-26 20:57:27 +08:00
hevinci
500b469bce Update AssetBundleBuilder
增加PackageVersion构建参数。
2022-10-26 19:51:29 +08:00
hevinci
49c242e7bc Update AssetBundleBuilder
检测输出目录文件路径过长导致的异常。
2022-10-25 19:07:48 +08:00
hevinci
2d72d6dbc9 Update AssetSystem 2022-10-25 15:56:07 +08:00
hevinci
1f3e55ebea Update DownloadSystem
下载错误提示增加HTTP Response Code
2022-10-25 14:33:21 +08:00
hevinci
0ecb37419b Update AssetSystem 2022-10-24 19:09:16 +08:00
hevinci
c758bf6530 Update AssetSystem 2022-10-24 15:39:04 +08:00
hevinci
46d985a720 Update AssetBundleDebugger
调试窗口增加调试信息导出按钮。
2022-10-22 18:23:40 +08:00
hevinci
9404882fc7 Update AssetBundleDebugger
调试窗口增加资源对象的加载耗时统计和显示
2022-10-22 17:47:06 +08:00
hevinci
ec1c3d6070 Update runtime code 2022-10-22 17:46:46 +08:00
hevinci
8eb7816e30 Update AssetBundleDebugger
界面增加了包裹名称显示列。
2022-10-22 15:39:26 +08:00
hevinci
c196e44bc6 Update runtime code 2022-10-22 15:38:51 +08:00
hevinci
989d88f7d3 Update runtime code
修复资源回收无效的问题。
2022-10-22 15:37:53 +08:00
hevinci
cb4ebb6306 Update document 2022-10-22 10:51:14 +08:00
790 changed files with 142702 additions and 19460 deletions

View File

@@ -2,6 +2,220 @@
All notable changes to this package will be documented in this file. All notable changes to this package will be documented in this file.
## [1.4.2-preview] - 2023-01-03
### Fixed
- 修复了清单解析异步操作的进度条变化错误。
- 修复了更新资源清单错误计算超时时间的问题。
## [1.4.1-preview] - 2022-12-26
### Fixed
- 修复了开启UniqueBundleName选项后SBP构建报错的问题。
### Added
- 新增了AssetsPackage.PreDownloadPackageAsync()方法
````c#
/// <summary>
/// 预下载指定版本的包裹资源
/// </summary>
/// <param name="packageVersion">下载的包裹版本</param>
/// <param name="timeout">超时时间默认值60秒</param>
public PreDownloadPackageOperation PreDownloadPackageAsync(string packageVersion, int timeout = 60)
````
- 新增了OperationHandleBase.GetDownloadReport()方法
````c#
/// <summary>
/// 获取下载报告
/// </summary>
public DownloadReport GetDownloadReport();
````
### Changed
- 优化了资源清单更新流程,支持缓存下载的清单。
- 优化了清单文件的解析流程,支持分帧解析避免卡顿。
- 优化了缓存文件的验证流程,支持分帧处理。
- 初始化的时候支持覆盖安装检测,然后清理所有的缓存清单文件。
- ClearPackageUnusedCacheFilesAsync重名为ClearUnusedCacheFilesAsync
## [1.4.0-preview] - 2022-12-04
### Fixed
- (#46)修复了资源包初始化失败之后,再次初始化发生异常的问题。
- 修复了在初始化失败的之后销毁YooAssets会报异常的问题。
### Changed
- 优化了资源收集界面,可以选择显示中文别名。
- **优化了补丁清单序列化方式,由文本数据修改为二进制数据。**
- 资源操作句柄增加using支持。
## [1.3.7] - 2022-11-26
全新的太空战机Demo !
### Fixed
- (#45)修复了package列表更新触发的异常。
### Added
- 新增了YooAssets.Destroy()资源系统销毁方法。
```C#
/// <summary>
/// 销毁资源系统
/// </summary>
public static void Destroy();
```
### Changed
- 优化了资源收集规则,原生文件打包名称现在已经包含文件后缀名。
- 优化了资源收集规则非原生文件收集器自动移除Unity无法识别的文件。
- 优化了调试信息窗口,列表元素的加载状态显示为文本。
## [1.3.5] - 2022-11-19
### Fixed
- 修复了同步接口加载加密文件失败的问题。
### Added
- 新增了方法AssetsPackage.ClearPackageUnusedCacheFilesAsync()
```c#
/// <summary>
/// 清理本地包裹未使用的缓存文件
/// </summary>
public ClearPackageUnusedCacheFilesOperation ClearPackageUnusedCacheFilesAsync()
```
- 新增了方法AssetsPackage.LoadRawFileAsync()
```c#
/// <summary>
/// 异步加载原生文件
/// </summary>
/// <param name="location">资源的定位地址</param>
public RawFileOperationHandle LoadRawFileAsync(string location)
```
- 新增了方法AssetsPackage.LoadRawFileSync()
```c#
/// <summary>
/// 同步加载原生文件
/// </summary>
/// <param name="location">资源的定位地址</param>
public RawFileOperationHandle LoadRawFileSync(string location)
```
### Changed
- 重命名AssetsPackage.UpdateStaticVersionAsync()为AssetsPackage.UpdatePackageVersionAsync();
- 重命名AssetsPackage.UpdateManifestAsync()为AssetsPackage.UpdatePackageManifestAsync();
### Removed
- 移除了方法YooAssets.ClearUnusedCacheFiles()
- 移除了方法AssetsPackage.GetRawFileAsync()
## [1.3.4] - 2022-11-04
### Fixed
- (#29)修复了EditorHelper中根据guid找uxml有时候会出错的问题。
- (#37)修复了在修改GroupName和GroupDesc时左侧Group栏显示没刷新的问题。
- (#38)修复了工程里没有shader的话SBP构建会报异常的问题。
### Added
- 新增了AssetsPackage.CheckPackageContentsAsync()方法
```c#
/// <summary>
/// 检查本地包裹内容的完整性
/// </summary>
public CheckPackageContentsOperation CheckPackageContentsAsync()
```
### Changed
- 优化了HostPlayMode的初始化逻辑优先读取沙盒内的清单如果不存在则读取内置清单。
- 重写了文件的加密和解密逻辑。
```c#
public interface IDecryptionServices
{
/// <summary>
/// 文件偏移解密方法
/// </summary>
ulong LoadFromFileOffset(DecryptFileInfo fileInfo);
/// <summary>
/// 文件内存解密方法
/// </summary>
byte[] LoadFromMemory(DecryptFileInfo fileInfo);
/// <summary>
/// 文件流解密方法
/// </summary>
System.IO.FileStream LoadFromStream(DecryptFileInfo fileInfo);
/// <summary>
/// 文件流解密的托管缓存大小
/// </summary>
uint GetManagedReadBufferSize();
}
```
- AssetBundleBuilder界面增加了构建版本选项。
### Removed
- 移除了AssetsPackage.WeaklyUpdateManifestAsync()方法。
## [1.3.3] - 2022-10-27
### Fixed
- 修复了资源回收方法无效的问题。
### Added
- 新增了PackageVersion构建参数。
````c#
public class BuildParameters
{
/// <summary>
/// 构建的包裹版本
/// </summary>
public string PackageVersion;
}
````
### Changed
- AssetBundleDebugger窗口增加了包裹名称显示列。
- AssetBundleDebugger窗口增加资源对象的加载耗时统计和显示。
- AssetBundleDebugger窗口增加帧调试数据导出功能。
- AssetBundleBuilder构建流程增加输出目录文件路径过长的检测。
- 下载器返回的错误提示增加HTTP Response Code。
- UpdateStaticVersionOperation.PackageCRC重名为UpdateStaticVersionOperation.PackageVersion。
- AssetPackage.GetHumanReadableVersion()重名为AssetPackage.GetPackageVersion()
## [1.3.2] - 2022-10-22 ## [1.3.2] - 2022-10-22
### Fixed ### Fixed

View File

@@ -56,6 +56,7 @@ namespace YooAsset.Editor
new TaskBuilding(), //开始执行构建 new TaskBuilding(), //开始执行构建
new TaskVerifyBuildResult(), //验证构建结果 new TaskVerifyBuildResult(), //验证构建结果
new TaskEncryption(), //加密资源文件 new TaskEncryption(), //加密资源文件
new TaskUpdateBuildInfo(), //更新构建信息
new TaskCreatePatchManifest(), //创建清单文件 new TaskCreatePatchManifest(), //创建清单文件
new TaskCreateReport(), //创建报告文件 new TaskCreateReport(), //创建报告文件
new TaskCreatePatchPackage(), //制作补丁包 new TaskCreatePatchPackage(), //制作补丁包
@@ -71,6 +72,7 @@ namespace YooAsset.Editor
new TaskBuilding_SBP(), //开始执行构建 new TaskBuilding_SBP(), //开始执行构建
new TaskVerifyBuildResult_SBP(), //验证构建结果 new TaskVerifyBuildResult_SBP(), //验证构建结果
new TaskEncryption(), //加密资源文件 new TaskEncryption(), //加密资源文件
new TaskUpdateBuildInfo(), //更新构建信息
new TaskCreatePatchManifest(), //创建清单文件 new TaskCreatePatchManifest(), //创建清单文件
new TaskCreateReport(), //创建报告文件 new TaskCreateReport(), //创建报告文件
new TaskCreatePatchPackage(), //制作补丁包 new TaskCreatePatchPackage(), //制作补丁包
@@ -86,7 +88,6 @@ namespace YooAsset.Editor
var buildResult = BuildRunner.Run(pipeline, _buildContext); var buildResult = BuildRunner.Run(pipeline, _buildContext);
if (buildResult.Success) if (buildResult.Success)
{ {
buildResult.OutputPackageCRC = buildParametersContext.OutputPackageCRC;
buildResult.OutputPackageDirectory = buildParametersContext.GetPackageOutputDirectory(); buildResult.OutputPackageDirectory = buildParametersContext.GetPackageOutputDirectory();
Debug.Log($"{buildParameters.BuildMode} pipeline build succeed !"); Debug.Log($"{buildParameters.BuildMode} pipeline build succeed !");
} }

View File

@@ -64,27 +64,8 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public static string MakePipelineOutputDirectory(string outputRoot, string buildPackage, BuildTarget buildTarget, EBuildMode buildMode) public static string MakePipelineOutputDirectory(string outputRoot, string buildPackage, BuildTarget buildTarget, EBuildMode buildMode)
{ {
string result = $"{outputRoot}/{buildPackage}/{buildTarget}/{YooAssetSettings.OutputFolderName}"; string outputDirectory = $"{outputRoot}/{buildPackage}/{buildTarget}/{YooAssetSettings.OutputFolderName}";
if (buildMode == EBuildMode.DryRunBuild) return outputDirectory;
result += $"_{EBuildMode.DryRunBuild}";
else if (buildMode == EBuildMode.SimulateBuild)
result += $"_{EBuildMode.SimulateBuild}";
return result;
}
/// <summary>
/// 加载补丁清单文件
/// </summary>
internal static PatchManifest LoadPatchManifestFile(string fileDirectory, string packageName, string packageCRC)
{
string filePath = $"{fileDirectory}/{YooAssetSettingsData.GetPatchManifestFileName(packageName, packageCRC)}";
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

@@ -27,6 +27,7 @@ namespace YooAsset.Editor
private TextField _buildOutputField; private TextField _buildOutputField;
private EnumField _buildPipelineField; private EnumField _buildPipelineField;
private EnumField _buildModeField; private EnumField _buildModeField;
private TextField _buildVersionField;
private PopupField<string> _buildPackageField; private PopupField<string> _buildPackageField;
private PopupField<string> _encryptionField; private PopupField<string> _encryptionField;
private EnumField _compressionField; private EnumField _compressionField;
@@ -91,6 +92,10 @@ namespace YooAsset.Editor
RefreshWindow(); RefreshWindow();
}); });
// 构建版本
_buildVersionField = root.Q<TextField>("BuildVersion");
_buildVersionField.SetValueWithoutNotify(GetBuildPackageVersion());
// 构建包裹 // 构建包裹
var buildPackageContainer = root.Q("BuildPackageContainer"); var buildPackageContainer = root.Q("BuildPackageContainer");
if (_buildPackageNames.Count > 0) if (_buildPackageNames.Count > 0)
@@ -255,7 +260,8 @@ namespace YooAsset.Editor
buildParameters.BuildTarget = _buildTarget; buildParameters.BuildTarget = _buildTarget;
buildParameters.BuildPipeline = AssetBundleBuilderSettingData.Setting.BuildPipeline; buildParameters.BuildPipeline = AssetBundleBuilderSettingData.Setting.BuildPipeline;
buildParameters.BuildMode = AssetBundleBuilderSettingData.Setting.BuildMode; buildParameters.BuildMode = AssetBundleBuilderSettingData.Setting.BuildMode;
buildParameters.BuildPackage = AssetBundleBuilderSettingData.Setting.BuildPackage; buildParameters.PackageName = AssetBundleBuilderSettingData.Setting.BuildPackage;
buildParameters.PackageVersion = _buildVersionField.value;
buildParameters.VerifyBuildingResult = true; buildParameters.VerifyBuildingResult = true;
buildParameters.EncryptionServices = CreateEncryptionServicesInstance(); buildParameters.EncryptionServices = CreateEncryptionServicesInstance();
buildParameters.CompressOption = AssetBundleBuilderSettingData.Setting.CompressOption; buildParameters.CompressOption = AssetBundleBuilderSettingData.Setting.CompressOption;
@@ -277,6 +283,13 @@ namespace YooAsset.Editor
} }
} }
// 构建版本相关
private string GetBuildPackageVersion()
{
int totalMinutes = DateTime.Now.Hour * 60 + DateTime.Now.Minute;
return DateTime.Now.ToString("yyyy-MM-dd") + "-" + totalMinutes;
}
// 构建包裹相关 // 构建包裹相关
private int GetDefaultPackageIndex(string packageName) private int GetDefaultPackageIndex(string packageName)
{ {

View File

@@ -6,6 +6,7 @@
<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:EnumField label="Build Pipeline" name="BuildPipeline" />
<uie:EnumField label="Build Mode" name="BuildMode" /> <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="BuildPackageContainer" style="height: 24px;" />
<ui:VisualElement name="EncryptionContainer" 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" />

View File

@@ -1,4 +1,5 @@
using UnityEditor; using UnityEditor;
using UnityEngine;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
@@ -9,20 +10,21 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public static string SimulateBuild(string packageName) public static string SimulateBuild(string packageName)
{ {
Debug.Log($"Begin to create simulate package : {packageName}");
string defaultOutputRoot = AssetBundleBuilderHelper.GetDefaultOutputRoot(); string defaultOutputRoot = AssetBundleBuilderHelper.GetDefaultOutputRoot();
BuildParameters buildParameters = new BuildParameters(); BuildParameters buildParameters = new BuildParameters();
buildParameters.OutputRoot = defaultOutputRoot; buildParameters.OutputRoot = defaultOutputRoot;
buildParameters.BuildTarget = EditorUserBuildSettings.activeBuildTarget; buildParameters.BuildTarget = EditorUserBuildSettings.activeBuildTarget;
buildParameters.BuildMode = EBuildMode.SimulateBuild; buildParameters.BuildMode = EBuildMode.SimulateBuild;
buildParameters.BuildPackage = packageName; buildParameters.PackageName = packageName;
buildParameters.PackageVersion = "Simulate";
AssetBundleBuilder builder = new AssetBundleBuilder(); AssetBundleBuilder builder = new AssetBundleBuilder();
var buildResult = builder.Run(buildParameters); var buildResult = builder.Run(buildParameters);
if (buildResult.Success) if (buildResult.Success)
{ {
string pipelineOutputDirectory = AssetBundleBuilderHelper.MakePipelineOutputDirectory(buildParameters.OutputRoot, buildParameters.BuildPackage, buildParameters.BuildTarget, buildParameters.BuildMode); string manifestFileName = YooAssetSettingsData.GetManifestBinaryFileName(buildParameters.PackageName, buildParameters.PackageVersion);
string manifestFileName = YooAssetSettingsData.GetPatchManifestFileName(buildParameters.BuildPackage, buildResult.OutputPackageCRC); string manifestFilePath = $"{buildResult.OutputPackageDirectory}/{manifestFileName}";
string manifestFilePath = $"{pipelineOutputDirectory}/{manifestFileName}";
return manifestFilePath; return manifestFilePath;
} }
else else

View File

@@ -175,8 +175,7 @@ namespace YooAsset.Editor
if (IsShaderAsset) if (IsShaderAsset)
{ {
string shareBundleName = YooAssetSettingsData.GetUnityShadersBundleFullName(); _shareBundleName = YooAssetSettingsData.GetUnityShadersBundleFullName(uniqueBundleName, packageName);
_shareBundleName = EditorTools.GetRegularPath(shareBundleName).ToLower();
} }
else else
{ {
@@ -184,15 +183,16 @@ namespace YooAsset.Editor
{ {
IPackRule packRule = PackDirectory.StaticPackRule; IPackRule packRule = PackDirectory.StaticPackRule;
var bundleName = packRule.GetBundleName(new PackRuleData(AssetPath)); var bundleName = packRule.GetBundleName(new PackRuleData(AssetPath));
var shareBundleName = $"share_{bundleName}.{YooAssetSettingsData.Setting.AssetBundleFileVariant}"; if (YooAssetSettingsData.Setting.RegularBundleName)
_shareBundleName = EditorTools.GetRegularPath(shareBundleName).ToLower(); bundleName = EditorTools.GetRegularPath(bundleName).Replace('/', '_').Replace('.', '_').ToLower();
} else
} bundleName = EditorTools.GetRegularPath(bundleName).ToLower();
if (uniqueBundleName) if (uniqueBundleName)
{ _shareBundleName = $"{packageName.ToLower()}_share_{bundleName}.{YooAssetSettingsData.Setting.AssetBundleFileVariant}";
if (string.IsNullOrEmpty(_shareBundleName) == false) else
_shareBundleName = $"{packageName.ToLower()}_{_shareBundleName}"; _shareBundleName = $"share_{bundleName}.{YooAssetSettingsData.Setting.AssetBundleFileVariant}";
}
} }
} }
else else
@@ -200,12 +200,17 @@ namespace YooAsset.Editor
if (IsRawAsset) if (IsRawAsset)
{ {
string mainBundleName = $"{_mainBundleName}.{YooAssetSettingsData.Setting.RawFileVariant}"; string mainBundleName = $"{_mainBundleName}.{YooAssetSettingsData.Setting.RawFileVariant}";
_mainBundleName = EditorTools.GetRegularPath(mainBundleName).ToLower(); _mainBundleName = mainBundleName.ToLower();
} }
else else
{ {
string mainBundleName = $"{_mainBundleName}.{YooAssetSettingsData.Setting.AssetBundleFileVariant}"; string mainBundleName = $"{_mainBundleName}.{YooAssetSettingsData.Setting.AssetBundleFileVariant}";
_mainBundleName = EditorTools.GetRegularPath(mainBundleName).ToLower(); ; _mainBundleName = mainBundleName.ToLower(); ;
}
if (uniqueBundleName)
{
_mainBundleName = $"{packageName.ToLower()}_{_mainBundleName}";
} }
} }
} }

View File

@@ -8,6 +8,40 @@ namespace YooAsset.Editor
{ {
public class BuildBundleInfo public class BuildBundleInfo
{ {
public class BuildPatchInfo
{
/// <summary>
/// 构建内容的哈希值
/// </summary>
public string ContentHash { set; get; }
/// <summary>
/// 文件哈希值
/// </summary>
public string PatchFileHash { set; get; }
/// <summary>
/// 文件哈希值
/// </summary>
public string PatchFileCRC { set; get; }
/// <summary>
/// 文件哈希值
/// </summary>
public long PatchFileSize { set; get; }
/// <summary>
/// 构建输出的文件路径
/// </summary>
public string BuildOutputFilePath { set; get; }
/// <summary>
/// 补丁包输出文件路径
/// </summary>
public string PatchOutputFilePath { set; get; }
}
/// <summary> /// <summary>
/// 资源包名称 /// 资源包名称
/// </summary> /// </summary>
@@ -19,6 +53,22 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public readonly List<BuildAssetInfo> BuildinAssets = new List<BuildAssetInfo>(); public readonly List<BuildAssetInfo> BuildinAssets = new List<BuildAssetInfo>();
/// <summary>
/// 补丁文件信息
/// </summary>
public readonly BuildPatchInfo PatchInfo = new BuildPatchInfo();
/// <summary>
/// Bundle文件的加载方法
/// </summary>
public EBundleLoadMethod LoadMethod { set; get; }
/// <summary>
/// 加密生成文件的路径
/// 注意:如果未加密该路径为空
/// </summary>
public string EncryptedFilePath { set; get; }
/// <summary> /// <summary>
/// 是否为原生文件 /// 是否为原生文件
/// </summary> /// </summary>
@@ -36,9 +86,18 @@ namespace YooAsset.Editor
} }
/// <summary> /// <summary>
/// 构建内容哈希值 /// 是否为加密文件
/// </summary> /// </summary>
public string ContentHash { set; get; } = "00000000000000000000000000000000"; //32位 public bool IsEncryptedFile
{
get
{
if (string.IsNullOrEmpty(EncryptedFilePath))
return false;
else
return true;
}
}
public BuildBundleInfo(string bundleName) public BuildBundleInfo(string bundleName)
@@ -117,5 +176,21 @@ namespace YooAsset.Editor
build.assetNames = GetBuildinAssetPaths(); build.assetNames = GetBuildinAssetPaths();
return build; return build;
} }
/// <summary>
/// 创建PatchBundle类
/// </summary>
internal PatchBundle CreatePatchBundle()
{
PatchBundle patchBundle = new PatchBundle();
patchBundle.BundleName = BundleName;
patchBundle.FileHash = PatchInfo.PatchFileHash;
patchBundle.FileCRC = PatchInfo.PatchFileCRC;
patchBundle.FileSize = PatchInfo.PatchFileSize;
patchBundle.IsRawFile = IsRawFile;
patchBundle.LoadMethod = (byte)LoadMethod;
patchBundle.Tags = GetBundleTags();
return patchBundle;
}
} }
} }

View File

@@ -64,18 +64,6 @@ namespace YooAsset.Editor
return result; return result;
} }
/// <summary>
/// 获取资源包的分类标签列表
/// </summary>
public string[] GetBundleTags(string bundleName)
{
if (TryGetBundleInfo(bundleName, out BuildBundleInfo bundleInfo))
{
return bundleInfo.GetBundleTags();
}
throw new Exception($"Not found {nameof(BuildBundleInfo)} : {bundleName}");
}
/// <summary> /// <summary>
/// 获取AssetBundle内构建的资源路径列表 /// 获取AssetBundle内构建的资源路径列表
/// </summary> /// </summary>

View File

@@ -57,14 +57,14 @@ namespace YooAsset.Editor
public EBuildMode BuildMode; public EBuildMode BuildMode;
/// <summary> /// <summary>
/// 构建的Package名称 /// 构建的包裹名称
/// </summary> /// </summary>
public string BuildPackage; public string PackageName;
/// <summary> /// <summary>
/// 人类可读的版本信息 /// 构建的包裹版本
/// </summary> /// </summary>
public string HumanReadableVersion; public string PackageVersion;
/// <summary> /// <summary>

View File

@@ -11,30 +11,12 @@ namespace YooAsset.Editor
private string _pipelineOutputDirectory = string.Empty; private string _pipelineOutputDirectory = string.Empty;
private string _packageOutputDirectory = string.Empty; private string _packageOutputDirectory = string.Empty;
private string _outputPackageCRC = string.Empty;
/// <summary> /// <summary>
/// 构建参数 /// 构建参数
/// </summary> /// </summary>
public BuildParameters Parameters { private set; get; } public BuildParameters Parameters { private set; get; }
/// <summary>
/// 构建输出的包裹清单哈希值
/// </summary>
public string OutputPackageCRC
{
get
{
if (string.IsNullOrEmpty(_outputPackageCRC))
throw new Exception("Output package file CRC32 is empty !");
return _outputPackageCRC;
}
set
{
_outputPackageCRC = value;
}
}
public BuildParametersContext(BuildParameters parameters) public BuildParametersContext(BuildParameters parameters)
{ {
@@ -49,7 +31,7 @@ namespace YooAsset.Editor
{ {
if (string.IsNullOrEmpty(_pipelineOutputDirectory)) if (string.IsNullOrEmpty(_pipelineOutputDirectory))
{ {
_pipelineOutputDirectory = AssetBundleBuilderHelper.MakePipelineOutputDirectory(Parameters.OutputRoot, Parameters.BuildPackage, Parameters.BuildTarget, Parameters.BuildMode); _pipelineOutputDirectory = AssetBundleBuilderHelper.MakePipelineOutputDirectory(Parameters.OutputRoot, Parameters.PackageName, Parameters.BuildTarget, Parameters.BuildMode);
} }
return _pipelineOutputDirectory; return _pipelineOutputDirectory;
} }
@@ -61,7 +43,7 @@ namespace YooAsset.Editor
{ {
if (string.IsNullOrEmpty(_packageOutputDirectory)) if (string.IsNullOrEmpty(_packageOutputDirectory))
{ {
_packageOutputDirectory = $"{Parameters.OutputRoot}/{Parameters.BuildPackage}/{Parameters.BuildTarget}/{OutputPackageCRC}"; _packageOutputDirectory = $"{Parameters.OutputRoot}/{Parameters.PackageName}/{Parameters.BuildTarget}/{Parameters.PackageVersion}";
} }
return _packageOutputDirectory; return _packageOutputDirectory;
} }

View File

@@ -1,6 +1,7 @@
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
@@ -56,6 +57,9 @@ 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.CreateFile(savePath, json); FileUtility.CreateFile(savePath, json);
} }

View File

@@ -8,21 +8,6 @@ namespace YooAsset.Editor
[Serializable] [Serializable]
public class ReportBundleInfo public class ReportBundleInfo
{ {
public class FlagsData
{
public bool IsEncrypted { private set; get; }
public bool IsBuildin { private set; get; }
public bool IsRawFile { private set; get; }
public FlagsData(bool isEncrypted, bool isBuildin, bool isRawFile)
{
IsEncrypted = isEncrypted;
IsBuildin = isBuildin;
IsRawFile = isRawFile;
}
}
private FlagsData _flagData;
/// <summary> /// <summary>
/// 资源包名称 /// 资源包名称
/// </summary> /// </summary>
@@ -48,33 +33,21 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public long FileSize; public long FileSize;
/// <summary>
/// 是否为原生文件
/// </summary>
public bool IsRawFile;
/// <summary>
/// 加载方法
/// </summary>
public EBundleLoadMethod LoadMethod;
/// <summary> /// <summary>
/// Tags /// Tags
/// </summary> /// </summary>
public string[] Tags; public string[] Tags;
/// <summary>
/// Flags
/// </summary>
public int Flags;
/// <summary>
/// 获取标志位的解析数据
/// </summary>
public FlagsData GetFlagData()
{
if (_flagData == null)
{
BitMask32 value = Flags;
bool isEncrypted = value.Test(0);
bool isBuildin = value.Test(1);
bool isRawFile = value.Test(2);
_flagData = new FlagsData(isEncrypted, isBuildin, isRawFile);
}
return _flagData;
}
/// <summary> /// <summary>
/// 获取资源分类标签的字符串 /// 获取资源分类标签的字符串
/// </summary> /// </summary>
@@ -85,16 +58,5 @@ namespace YooAsset.Editor
else else
return string.Empty; return string.Empty;
} }
/// <summary>
/// 是否为原生文件
/// </summary>
public bool IsRawFile()
{
if (System.IO.Path.GetExtension(BundleName) == $".{YooAssetSettingsData.Setting.RawFileVariant}")
return true;
else
return false;
}
} }
} }

View File

@@ -44,9 +44,14 @@ namespace YooAsset.Editor
public EBuildMode BuildMode; public EBuildMode BuildMode;
/// <summary> /// <summary>
/// 构建包裹 /// 构建包裹名称
/// </summary> /// </summary>
public string BuildPackage; public string BuildPackageName;
/// <summary>
/// 构建包裹版本
/// </summary>
public string BuildPackageVersion;
/// <summary> /// <summary>
/// 启用可寻址资源定位 /// 启用可寻址资源定位

View File

@@ -25,10 +25,5 @@ namespace YooAsset.Editor
/// 输出的补丁包目录 /// 输出的补丁包目录
/// </summary> /// </summary>
public string OutputPackageDirectory; public string OutputPackageDirectory;
/// <summary>
/// 输出的包裹清单哈希值
/// </summary>
public string OutputPackageCRC;
} }
} }

View File

@@ -25,16 +25,19 @@ namespace YooAsset.Editor
if (buildMode == EBuildMode.SimulateBuild) if (buildMode == EBuildMode.SimulateBuild)
return; return;
// 开始构建
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory(); string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
BuildAssetBundleOptions buildOptions = buildParametersContext.GetPipelineBuildOptions(); BuildAssetBundleOptions buildOptions = buildParametersContext.GetPipelineBuildOptions();
AssetBundleManifest buildResults = BuildPipeline.BuildAssetBundles(pipelineOutputDirectory, buildMapContext.GetPipelineBuilds(), buildOptions, buildParametersContext.Parameters.BuildTarget); AssetBundleManifest buildResults = BuildPipeline.BuildAssetBundles(pipelineOutputDirectory, buildMapContext.GetPipelineBuilds(), buildOptions, buildParametersContext.Parameters.BuildTarget);
if (buildResults == null) if (buildResults == null)
{
throw new Exception("构建过程中发生错误!"); throw new Exception("构建过程中发生错误!");
}
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild) if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
{ {
string unityOutputManifestFilePath = $"{buildParametersContext.GetPipelineOutputDirectory()}/{YooAssetSettings.OutputFolderName}"; string unityOutputManifestFilePath = $"{pipelineOutputDirectory}/{YooAssetSettings.OutputFolderName}";
if(System.IO.File.Exists(unityOutputManifestFilePath) == false) if (System.IO.File.Exists(unityOutputManifestFilePath) == false)
throw new Exception("构建过程中发生严重错误!请查阅上下文日志!"); throw new Exception("构建过程中发生严重错误!请查阅上下文日志!");
} }
@@ -43,10 +46,10 @@ namespace YooAsset.Editor
buildResultContext.UnityManifest = buildResults; buildResultContext.UnityManifest = buildResults;
context.SetContextObject(buildResultContext); context.SetContextObject(buildResultContext);
// 拷贝原生文件
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild) if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
{ {
CopyRawBundle(buildMapContext, buildParametersContext); CopyRawBundle(buildMapContext, buildParametersContext);
UpdateBuildBundleInfo(buildMapContext, buildParametersContext, buildResultContext);
} }
} }
@@ -69,29 +72,5 @@ namespace YooAsset.Editor
} }
} }
} }
/// <summary>
/// 更新构建结果
/// </summary>
private void UpdateBuildBundleInfo(BuildMapContext buildMapContext, BuildParametersContext buildParametersContext, BuildResultContext buildResult)
{
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
foreach (var bundleInfo in buildMapContext.BundleInfos)
{
if (bundleInfo.IsRawFile)
{
string filePath = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}";
bundleInfo.ContentHash = HashUtility.FileMD5(filePath);
}
else
{
var hash = buildResult.UnityManifest.GetAssetBundleHash(bundleInfo.BundleName);
if (hash.isValid)
bundleInfo.ContentHash = hash.ToString();
else
throw new Exception($"Not found bundle in build result : {bundleInfo.BundleName}");
}
}
}
} }
} }

View File

@@ -33,7 +33,7 @@ namespace YooAsset.Editor
// 开始构建 // 开始构建
IBundleBuildResults buildResults; IBundleBuildResults buildResults;
var buildParameters = buildParametersContext.GetSBPBuildParameters(); var buildParameters = buildParametersContext.GetSBPBuildParameters();
var shadersBunldeName = YooAssetSettingsData.GetUnityShadersBundleFullName(); var shadersBunldeName = YooAssetSettingsData.GetUnityShadersBundleFullName(buildMapContext.UniqueBundleName, buildParametersContext.Parameters.PackageName);
var taskList = SBPBuildTasks.Create(shadersBunldeName); var taskList = SBPBuildTasks.Create(shadersBunldeName);
ReturnCode exitCode = ContentPipeline.BuildAssetBundles(buildParameters, buildContent, out buildResults, taskList); ReturnCode exitCode = ContentPipeline.BuildAssetBundles(buildParameters, buildContent, out buildResults, taskList);
if (exitCode < 0) if (exitCode < 0)
@@ -46,10 +46,10 @@ namespace YooAsset.Editor
buildResultContext.Results = buildResults; buildResultContext.Results = buildResults;
context.SetContextObject(buildResultContext); context.SetContextObject(buildResultContext);
// 拷贝原生文件
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild) if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
{ {
CopyRawBundle(buildMapContext, buildParametersContext); CopyRawBundle(buildMapContext, buildParametersContext);
UpdateBuildBundleInfo(buildMapContext, buildParametersContext, buildResultContext);
} }
} }
@@ -72,29 +72,5 @@ namespace YooAsset.Editor
} }
} }
} }
/// <summary>
/// 更新构建结果
/// </summary>
private void UpdateBuildBundleInfo(BuildMapContext buildMapContext, BuildParametersContext buildParametersContext, BuildResultContext buildResult)
{
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
foreach (var bundleInfo in buildMapContext.BundleInfos)
{
if (bundleInfo.IsRawFile)
{
string filePath = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}";
bundleInfo.ContentHash = HashUtility.FileMD5(filePath);
}
else
{
// 注意当资源包的依赖列表发生变化的时候ContentHash也会发生变化
if (buildResult.Results.BundleInfos.TryGetValue(bundleInfo.BundleName, out var value))
bundleInfo.ContentHash = value.Hash.ToString();
else
throw new Exception($"Not found bundle in build result : {bundleInfo.BundleName}");
}
}
}
} }
} }

View File

@@ -12,25 +12,30 @@ namespace YooAsset.Editor
void IBuildTask.Run(BuildContext context) void IBuildTask.Run(BuildContext context)
{ {
var buildParametersContext = context.GetContextObject<BuildParametersContext>(); var buildParametersContext = context.GetContextObject<BuildParametersContext>();
if (buildParametersContext.Parameters.CopyBuildinFileOption != ECopyBuildinFileOption.None) var patchManifestContext = context.GetContextObject<PatchManifestContext>();
var buildMode = buildParametersContext.Parameters.BuildMode;
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
{ {
CopyBuildinFilesToStreaming(buildParametersContext); if (buildParametersContext.Parameters.CopyBuildinFileOption != ECopyBuildinFileOption.None)
{
CopyBuildinFilesToStreaming(buildParametersContext, patchManifestContext);
}
} }
} }
/// <summary> /// <summary>
/// 拷贝首包资源文件 /// 拷贝首包资源文件
/// </summary> /// </summary>
private void CopyBuildinFilesToStreaming(BuildParametersContext buildParametersContext) private void CopyBuildinFilesToStreaming(BuildParametersContext buildParametersContext, PatchManifestContext patchManifestContext)
{ {
ECopyBuildinFileOption option = buildParametersContext.Parameters.CopyBuildinFileOption; ECopyBuildinFileOption option = buildParametersContext.Parameters.CopyBuildinFileOption;
string packageOutputDirectory = buildParametersContext.GetPackageOutputDirectory(); string packageOutputDirectory = buildParametersContext.GetPackageOutputDirectory();
string streamingAssetsDirectory = AssetBundleBuilderHelper.GetStreamingAssetsFolderPath(); string streamingAssetsDirectory = AssetBundleBuilderHelper.GetStreamingAssetsFolderPath();
string buildPackageName = buildParametersContext.Parameters.BuildPackage; string buildPackageName = buildParametersContext.Parameters.PackageName;
string outputPackageCRC = buildParametersContext.OutputPackageCRC; string buildPackageVersion = buildParametersContext.Parameters.PackageVersion;
// 加载补丁清单 // 加载补丁清单
PatchManifest patchManifest = AssetBundleBuilderHelper.LoadPatchManifestFile(packageOutputDirectory, buildPackageName, outputPackageCRC); PatchManifest patchManifest = patchManifestContext.Manifest;
// 清空流目录 // 清空流目录
if (option == ECopyBuildinFileOption.ClearAndCopyAll || option == ECopyBuildinFileOption.ClearAndCopyByTags) if (option == ECopyBuildinFileOption.ClearAndCopyAll || option == ECopyBuildinFileOption.ClearAndCopyByTags)
@@ -40,17 +45,25 @@ namespace YooAsset.Editor
// 拷贝补丁清单文件 // 拷贝补丁清单文件
{ {
string manifestFileName = YooAssetSettingsData.GetPatchManifestFileName(buildPackageName, outputPackageCRC); string fileName = YooAssetSettingsData.GetManifestBinaryFileName(buildPackageName, buildPackageVersion);
string sourcePath = $"{packageOutputDirectory}/{manifestFileName}"; string sourcePath = $"{packageOutputDirectory}/{fileName}";
string destPath = $"{streamingAssetsDirectory}/{manifestFileName}"; string destPath = $"{streamingAssetsDirectory}/{fileName}";
EditorTools.CopyFile(sourcePath, destPath, true); EditorTools.CopyFile(sourcePath, destPath, true);
} }
// 拷贝静态版本文件 // 拷贝补丁清单哈希文件
{ {
string versionFileName = YooAssetSettingsData.GetStaticVersionFileName(buildPackageName); string fileName = YooAssetSettingsData.GetPackageHashFileName(buildPackageName, buildPackageVersion);
string sourcePath = $"{packageOutputDirectory}/{versionFileName}"; string sourcePath = $"{packageOutputDirectory}/{fileName}";
string destPath = $"{streamingAssetsDirectory}/{versionFileName}"; string destPath = $"{streamingAssetsDirectory}/{fileName}";
EditorTools.CopyFile(sourcePath, destPath, true);
}
// 拷贝补丁清单版本文件
{
string fileName = YooAssetSettingsData.GetPackageVersionFileName(buildPackageName);
string sourcePath = $"{packageOutputDirectory}/{fileName}";
string destPath = $"{streamingAssetsDirectory}/{fileName}";
EditorTools.CopyFile(sourcePath, destPath, true); EditorTools.CopyFile(sourcePath, destPath, true);
} }

View File

@@ -8,6 +8,11 @@ using UnityEditor.Build.Pipeline.Interfaces;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
public class PatchManifestContext : IContextObject
{
internal PatchManifest Manifest;
}
[TaskAttribute("创建补丁清单文件")] [TaskAttribute("创建补丁清单文件")]
public class TaskCreatePatchManifest : IBuildTask public class TaskCreatePatchManifest : IBuildTask
{ {
@@ -24,47 +29,67 @@ namespace YooAsset.Editor
var buildMapContext = context.GetContextObject<BuildMapContext>(); var buildMapContext = context.GetContextObject<BuildMapContext>();
var buildParametersContext = context.GetContextObject<BuildParametersContext>(); var buildParametersContext = context.GetContextObject<BuildParametersContext>();
var buildParameters = buildParametersContext.Parameters; var buildParameters = buildParametersContext.Parameters;
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory(); string packageOutputDirectory = buildParametersContext.GetPackageOutputDirectory();
// 创建新补丁清单 // 创建新补丁清单
PatchManifest patchManifest = new PatchManifest(); PatchManifest patchManifest = new PatchManifest();
patchManifest.FileVersion = YooAssetSettings.PatchManifestFileVersion; patchManifest.FileVersion = YooAssetSettings.PatchManifestFileVersion;
patchManifest.EnableAddressable = buildMapContext.EnableAddressable; patchManifest.EnableAddressable = buildMapContext.EnableAddressable;
patchManifest.OutputNameStyle = (int)buildParameters.OutputNameStyle; patchManifest.OutputNameStyle = (int)buildParameters.OutputNameStyle;
patchManifest.PackageName = buildParameters.BuildPackage; patchManifest.PackageName = buildParameters.PackageName;
patchManifest.HumanReadableVersion = buildParameters.HumanReadableVersion; patchManifest.PackageVersion = buildParameters.PackageVersion;
patchManifest.BundleList = GetAllPatchBundle(context); patchManifest.BundleList = GetAllPatchBundle(context);
patchManifest.AssetList = GetAllPatchAsset(context, patchManifest); patchManifest.AssetList = GetAllPatchAsset(context, patchManifest);
// 更新Unity内置资源包的引用关系 // 更新Unity内置资源包的引用关系
string shadersBunldeName = YooAssetSettingsData.GetUnityShadersBundleFullName(buildMapContext.UniqueBundleName, buildParameters.PackageName);
if (buildParameters.BuildPipeline == EBuildPipeline.ScriptableBuildPipeline) if (buildParameters.BuildPipeline == EBuildPipeline.ScriptableBuildPipeline)
{ {
if(buildParameters.BuildMode == EBuildMode.IncrementalBuild) if (buildParameters.BuildMode == EBuildMode.IncrementalBuild)
{ {
var buildResultContext = context.GetContextObject<TaskBuilding_SBP.BuildResultContext>(); var buildResultContext = context.GetContextObject<TaskBuilding_SBP.BuildResultContext>();
UpdateBuiltInBundleReference(patchManifest, buildResultContext.Results); UpdateBuiltInBundleReference(patchManifest, buildResultContext.Results, shadersBunldeName);
} }
} }
// 创建补丁清单文件 // 创建补丁清单文本文
string manifestFileTempName = YooAssetSettingsData.GetPatchManifestTempFileName(buildParameters.BuildPackage); {
string manifestFileTempPath = $"{pipelineOutputDirectory}/{manifestFileTempName}"; string fileName = YooAssetSettingsData.GetManifestJsonFileName(buildParameters.PackageName, buildParameters.PackageVersion);
BuildRunner.Log($"创建补丁清单文件:{manifestFileTempPath}"); string filePath = $"{packageOutputDirectory}/{fileName}";
PatchManifest.Serialize(manifestFileTempPath, patchManifest); PatchManifestTools.SerializeToJson(filePath, patchManifest);
BuildRunner.Log($"创建补丁清单文件:{filePath}");
}
// 计算补丁清单文件的CRC32 // 创建补丁清单二进制文件
buildParametersContext.OutputPackageCRC = HashUtility.FileCRC32(manifestFileTempPath); string packageHash;
{
string fileName = YooAssetSettingsData.GetManifestBinaryFileName(buildParameters.PackageName, buildParameters.PackageVersion);
string filePath = $"{packageOutputDirectory}/{fileName}";
PatchManifestTools.SerializeToBinary(filePath, patchManifest);
packageHash = HashUtility.FileMD5(filePath);
BuildRunner.Log($"创建补丁清单文件:{filePath}");
// 补丁清单文件重命名 PatchManifestContext patchManifestContext = new PatchManifestContext();
string manifestFileName = YooAssetSettingsData.GetPatchManifestFileName(buildParameters.BuildPackage, buildParametersContext.OutputPackageCRC); byte[] bytesData = FileUtility.ReadAllBytes(filePath);
string manifestFilePath = $"{pipelineOutputDirectory}/{manifestFileName}"; patchManifestContext.Manifest = PatchManifestTools.DeserializeFromBinary(bytesData);
EditorTools.FileMoveTo(manifestFileTempPath, manifestFilePath); context.SetContextObject(patchManifestContext);
}
// 创建静态版本文件 // 创建补丁清单哈希文件
string staticVersionFileName = YooAssetSettingsData.GetStaticVersionFileName(buildParameters.BuildPackage); {
string staticVersionFilePath = $"{pipelineOutputDirectory}/{staticVersionFileName}"; string fileName = YooAssetSettingsData.GetPackageHashFileName(buildParameters.PackageName, buildParameters.PackageVersion);
BuildRunner.Log($"创建静态版本文件:{staticVersionFilePath}"); string filePath = $"{packageOutputDirectory}/{fileName}";
FileUtility.CreateFile(staticVersionFilePath, buildParametersContext.OutputPackageCRC); FileUtility.CreateFile(filePath, packageHash);
BuildRunner.Log($"创建补丁清单哈希文件:{filePath}");
}
// 创建补丁清单版本文件
{
string fileName = YooAssetSettingsData.GetPackageVersionFileName(buildParameters.PackageName);
string filePath = $"{packageOutputDirectory}/{fileName}";
FileUtility.CreateFile(filePath, buildParameters.PackageVersion);
BuildRunner.Log($"创建补丁清单版本文件:{filePath}");
}
} }
/// <summary> /// <summary>
@@ -72,54 +97,17 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
private List<PatchBundle> GetAllPatchBundle(BuildContext context) private List<PatchBundle> GetAllPatchBundle(BuildContext context)
{ {
var buildParameters = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>(); var buildMapContext = context.GetContextObject<BuildMapContext>();
var encryptionContext = context.GetContextObject<TaskEncryption.EncryptionContext>(); var buildParametersContext = context.GetContextObject<BuildParametersContext>();
List<PatchBundle> result = new List<PatchBundle>(1000); List<PatchBundle> result = new List<PatchBundle>(1000);
foreach (var bundleInfo in buildMapContext.BundleInfos) foreach (var bundleInfo in buildMapContext.BundleInfos)
{ {
var bundleName = bundleInfo.BundleName; var patchBundle = bundleInfo.CreatePatchBundle();
string fileHash = GetBundleFileHash(bundleInfo, buildParameters);
string fileCRC = GetBundleFileCRC(bundleInfo, buildParameters);
long fileSize = GetBundleFileSize(bundleInfo, buildParameters);
string[] tags = buildMapContext.GetBundleTags(bundleName);
bool isEncrypted = encryptionContext.IsEncryptFile(bundleName);
bool isRawFile = bundleInfo.IsRawFile;
PatchBundle patchBundle = new PatchBundle(bundleName, fileHash, fileCRC, fileSize, tags);
patchBundle.SetFlagsValue(isRawFile, isEncrypted);
result.Add(patchBundle); result.Add(patchBundle);
} }
return result; return result;
} }
private string GetBundleFileHash(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext)
{
var buildMode = buildParametersContext.Parameters.BuildMode;
if (buildMode == EBuildMode.DryRunBuild || buildMode == EBuildMode.SimulateBuild)
return "00000000000000000000000000000000"; //32位
string filePath = $"{buildParametersContext.GetPipelineOutputDirectory()}/{bundleInfo.BundleName}";
return HashUtility.FileMD5(filePath);
}
private string GetBundleFileCRC(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext)
{
var buildMode = buildParametersContext.Parameters.BuildMode;
if (buildMode == EBuildMode.DryRunBuild || buildMode == EBuildMode.SimulateBuild)
return "00000000"; //8位
string filePath = $"{buildParametersContext.GetPipelineOutputDirectory()}/{bundleInfo.BundleName}";
return HashUtility.FileCRC32(filePath);
}
private long GetBundleFileSize(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext)
{
var buildMode = buildParametersContext.Parameters.BuildMode;
if (buildMode == EBuildMode.DryRunBuild || buildMode == EBuildMode.SimulateBuild)
return 0;
string filePath = $"{buildParametersContext.GetPipelineOutputDirectory()}/{bundleInfo.BundleName}";
return FileUtility.GetFileSize(filePath);
}
/// <summary> /// <summary>
/// 获取资源列表 /// 获取资源列表
@@ -178,10 +166,9 @@ namespace YooAsset.Editor
/// <summary> /// <summary>
/// 更新Unity内置资源包的引用关系 /// 更新Unity内置资源包的引用关系
/// </summary> /// </summary>
private void UpdateBuiltInBundleReference(PatchManifest patchManifest, IBundleBuildResults buildResults) private void UpdateBuiltInBundleReference(PatchManifest patchManifest, IBundleBuildResults buildResults, string shadersBunldeName)
{ {
// 获取所有依赖着色器资源包的资源包列表 // 获取所有依赖着色器资源包的资源包列表
string shadersBunldeName = YooAssetSettingsData.GetUnityShadersBundleFullName();
List<string> shaderBundleReferenceList = new List<string>(); List<string> shaderBundleReferenceList = new List<string>();
foreach (var valuePair in buildResults.BundleInfos) foreach (var valuePair in buildResults.BundleInfos)
{ {
@@ -189,6 +176,10 @@ namespace YooAsset.Editor
shaderBundleReferenceList.Add(valuePair.Key); shaderBundleReferenceList.Add(valuePair.Key);
} }
// 注意:没有任何资源依赖着色器
if (shaderBundleReferenceList.Count == 0)
return;
// 获取着色器资源包索引 // 获取着色器资源包索引
Predicate<PatchBundle> predicate = new Predicate<PatchBundle>(s => s.BundleName == shadersBunldeName); Predicate<PatchBundle> predicate = new Predicate<PatchBundle>(s => s.BundleName == shadersBunldeName);
int shaderBundleId = patchManifest.BundleList.FindIndex(predicate); int shaderBundleId = patchManifest.BundleList.FindIndex(predicate);

View File

@@ -9,47 +9,24 @@ namespace YooAsset.Editor
void IBuildTask.Run(BuildContext context) void IBuildTask.Run(BuildContext context)
{ {
var buildParameters = context.GetContextObject<BuildParametersContext>(); var buildParameters = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
var buildMode = buildParameters.Parameters.BuildMode; var buildMode = buildParameters.Parameters.BuildMode;
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild) if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
{ {
CopyPatchFiles(buildParameters); CopyPatchFiles(buildParameters, buildMapContext);
} }
} }
/// <summary> /// <summary>
/// 拷贝补丁文件到补丁包目录 /// 拷贝补丁文件到补丁包目录
/// </summary> /// </summary>
private void CopyPatchFiles(BuildParametersContext buildParametersContext) private void CopyPatchFiles(BuildParametersContext buildParametersContext, BuildMapContext buildMapContext)
{ {
var buildParameters = buildParametersContext.Parameters; var buildParameters = buildParametersContext.Parameters;
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory(); string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
string packageOutputDirectory = buildParametersContext.GetPackageOutputDirectory(); string packageOutputDirectory = buildParametersContext.GetPackageOutputDirectory();
BuildRunner.Log($"开始拷贝补丁文件到补丁包目录:{packageOutputDirectory}"); BuildRunner.Log($"开始拷贝补丁文件到补丁包目录:{packageOutputDirectory}");
// 拷贝Report文件
{
string reportFileName = YooAssetSettingsData.GetReportFileName(buildParameters.BuildPackage, buildParametersContext.OutputPackageCRC);
string sourcePath = $"{pipelineOutputDirectory}/{reportFileName}";
string destPath = $"{packageOutputDirectory}/{reportFileName}";
EditorTools.CopyFile(sourcePath, destPath, true);
}
// 拷贝补丁清单文件
{
string manifestFileName = YooAssetSettingsData.GetPatchManifestFileName(buildParameters.BuildPackage, buildParametersContext.OutputPackageCRC);
string sourcePath = $"{pipelineOutputDirectory}/{manifestFileName}";
string destPath = $"{packageOutputDirectory}/{manifestFileName}";
EditorTools.CopyFile(sourcePath, destPath, true);
}
// 拷贝静态版本文件
{
string versionFileName = YooAssetSettingsData.GetStaticVersionFileName(buildParameters.BuildPackage);
string sourcePath = $"{pipelineOutputDirectory}/{versionFileName}";
string destPath = $"{packageOutputDirectory}/{versionFileName}";
EditorTools.CopyFile(sourcePath, destPath, true);
}
if (buildParameters.BuildPipeline == EBuildPipeline.ScriptableBuildPipeline) if (buildParameters.BuildPipeline == EBuildPipeline.ScriptableBuildPipeline)
{ {
// 拷贝构建日志 // 拷贝构建日志
@@ -67,7 +44,7 @@ namespace YooAsset.Editor
EditorTools.CopyFile(sourcePath, destPath, true); EditorTools.CopyFile(sourcePath, destPath, true);
} }
} }
else else if (buildParameters.BuildPipeline == EBuildPipeline.BuiltinBuildPipeline)
{ {
// 拷贝UnityManifest序列化文件 // 拷贝UnityManifest序列化文件
{ {
@@ -83,16 +60,17 @@ namespace YooAsset.Editor
EditorTools.CopyFile(sourcePath, destPath, true); EditorTools.CopyFile(sourcePath, destPath, true);
} }
} }
else
{
throw new System.NotImplementedException();
}
// 拷贝所有补丁文件 // 拷贝所有补丁文件
int progressValue = 0; int progressValue = 0;
PatchManifest patchManifest = AssetBundleBuilderHelper.LoadPatchManifestFile(pipelineOutputDirectory, buildParameters.BuildPackage, buildParametersContext.OutputPackageCRC); int patchFileTotalCount = buildMapContext.BundleInfos.Count;
int patchFileTotalCount = patchManifest.BundleList.Count; foreach (var bundleInfo in buildMapContext.BundleInfos)
foreach (var patchBundle in patchManifest.BundleList)
{ {
string sourcePath = $"{pipelineOutputDirectory}/{patchBundle.BundleName}"; EditorTools.CopyFile(bundleInfo.PatchInfo.BuildOutputFilePath, bundleInfo.PatchInfo.PatchOutputFilePath, true);
string destPath = $"{packageOutputDirectory}/{patchBundle.FileName}";
EditorTools.CopyFile(sourcePath, destPath, true);
EditorTools.DisplayProgressBar("拷贝补丁文件", ++progressValue, patchFileTotalCount); EditorTools.DisplayProgressBar("拷贝补丁文件", ++progressValue, patchFileTotalCount);
} }
EditorTools.ClearProgressBar(); EditorTools.ClearProgressBar();

View File

@@ -12,24 +12,25 @@ namespace YooAsset.Editor
{ {
var buildParameters = context.GetContextObject<BuildParametersContext>(); var buildParameters = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>(); var buildMapContext = context.GetContextObject<BuildMapContext>();
var patchManifestContext = context.GetContextObject<PatchManifestContext>();
buildParameters.StopWatch(); buildParameters.StopWatch();
var buildMode = buildParameters.Parameters.BuildMode; var buildMode = buildParameters.Parameters.BuildMode;
if (buildMode != EBuildMode.SimulateBuild) if (buildMode != EBuildMode.SimulateBuild)
{ {
CreateReportFile(buildParameters, buildMapContext); CreateReportFile(buildParameters, buildMapContext, patchManifestContext);
} }
float buildSeconds = buildParameters.GetBuildingSeconds(); float buildSeconds = buildParameters.GetBuildingSeconds();
BuildRunner.Info($"Build time consuming {buildSeconds} seconds."); BuildRunner.Info($"Build time consuming {buildSeconds} seconds.");
} }
private void CreateReportFile(BuildParametersContext buildParametersContext, BuildMapContext buildMapContext) private void CreateReportFile(BuildParametersContext buildParametersContext, BuildMapContext buildMapContext, PatchManifestContext patchManifestContext)
{ {
var buildParameters = buildParametersContext.Parameters; var buildParameters = buildParametersContext.Parameters;
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory(); string packageOutputDirectory = buildParametersContext.GetPackageOutputDirectory();
PatchManifest patchManifest = AssetBundleBuilderHelper.LoadPatchManifestFile(pipelineOutputDirectory, buildParameters.BuildPackage, buildParametersContext.OutputPackageCRC); PatchManifest patchManifest = patchManifestContext.Manifest;
BuildReport buildReport = new BuildReport(); BuildReport buildReport = new BuildReport();
// 概述信息 // 概述信息
@@ -45,10 +46,10 @@ namespace YooAsset.Editor
buildReport.Summary.BuildTarget = buildParameters.BuildTarget; buildReport.Summary.BuildTarget = buildParameters.BuildTarget;
buildReport.Summary.BuildPipeline = buildParameters.BuildPipeline; buildReport.Summary.BuildPipeline = buildParameters.BuildPipeline;
buildReport.Summary.BuildMode = buildParameters.BuildMode; buildReport.Summary.BuildMode = buildParameters.BuildMode;
buildReport.Summary.BuildPackage = buildParameters.BuildPackage; buildReport.Summary.BuildPackageName = buildParameters.PackageName;
buildReport.Summary.BuildPackageVersion = buildParameters.PackageVersion;
buildReport.Summary.EnableAddressable = buildMapContext.EnableAddressable; buildReport.Summary.EnableAddressable = buildMapContext.EnableAddressable;
buildReport.Summary.UniqueBundleName = buildMapContext.UniqueBundleName; buildReport.Summary.UniqueBundleName = buildMapContext.UniqueBundleName;
buildReport.Summary.EncryptionServicesClassName = buildParameters.EncryptionServices == null ? buildReport.Summary.EncryptionServicesClassName = buildParameters.EncryptionServices == null ?
"null" : buildParameters.EncryptionServices.GetType().FullName; "null" : buildParameters.EncryptionServices.GetType().FullName;
@@ -97,17 +98,14 @@ namespace YooAsset.Editor
reportBundleInfo.FileCRC = patchBundle.FileCRC; reportBundleInfo.FileCRC = patchBundle.FileCRC;
reportBundleInfo.FileSize = patchBundle.FileSize; reportBundleInfo.FileSize = patchBundle.FileSize;
reportBundleInfo.Tags = patchBundle.Tags; reportBundleInfo.Tags = patchBundle.Tags;
reportBundleInfo.Flags = patchBundle.Flags; reportBundleInfo.IsRawFile = patchBundle.IsRawFile;
reportBundleInfo.LoadMethod = (EBundleLoadMethod)patchBundle.LoadMethod;
buildReport.BundleInfos.Add(reportBundleInfo); buildReport.BundleInfos.Add(reportBundleInfo);
} }
// 删除旧文件
string fileName = YooAssetSettingsData.GetReportFileName(buildParameters.BuildPackage, buildParametersContext.OutputPackageCRC);
string filePath = $"{pipelineOutputDirectory}/{fileName}";
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);
BuildRunner.Log($"资源构建报告文件创建完成:{filePath}"); BuildRunner.Log($"资源构建报告文件创建完成:{filePath}");
} }
@@ -181,7 +179,7 @@ namespace YooAsset.Editor
int fileCount = 0; int fileCount = 0;
foreach (var patchBundle in patchManifest.BundleList) foreach (var patchBundle in patchManifest.BundleList)
{ {
if (patchBundle.IsEncrypted) if (patchBundle.LoadMethod != (byte)EBundleLoadMethod.Normal)
fileCount++; fileCount++;
} }
return fileCount; return fileCount;
@@ -191,7 +189,7 @@ namespace YooAsset.Editor
long fileBytes = 0; long fileBytes = 0;
foreach (var patchBundle in patchManifest.BundleList) foreach (var patchBundle in patchManifest.BundleList)
{ {
if (patchBundle.IsEncrypted) if (patchBundle.LoadMethod != (byte)EBundleLoadMethod.Normal)
fileBytes += patchBundle.FileSize; fileBytes += patchBundle.FileSize;
} }
return fileBytes; return fileBytes;

View File

@@ -9,19 +9,6 @@ namespace YooAsset.Editor
[TaskAttribute("资源包加密")] [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<BuildParametersContext>();
@@ -30,65 +17,52 @@ namespace YooAsset.Editor
var buildMode = buildParameters.Parameters.BuildMode; var buildMode = buildParameters.Parameters.BuildMode;
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild) if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
{ {
EncryptionContext encryptionContext = new EncryptionContext(); EncryptingBundleFiles(buildParameters, buildMapContext);
encryptionContext.EncryptList = EncryptFiles(buildParameters, buildMapContext);
context.SetContextObject(encryptionContext);
}
else
{
EncryptionContext encryptionContext = new EncryptionContext();
encryptionContext.EncryptList = new List<string>();
context.SetContextObject(encryptionContext);
} }
} }
/// <summary> /// <summary>
/// 加密文件 /// 加密文件
/// </summary> /// </summary>
private List<string> EncryptFiles(BuildParametersContext buildParametersContext, BuildMapContext buildMapContext) private void EncryptingBundleFiles(BuildParametersContext buildParametersContext, BuildMapContext buildMapContext)
{ {
var encryptionServices = buildParametersContext.Parameters.EncryptionServices; var encryptionServices = buildParametersContext.Parameters.EncryptionServices;
// 加密资源列表
List<string> encryptList = new List<string>();
// 如果没有设置加密类 // 如果没有设置加密类
if (encryptionServices == null) if (encryptionServices == null)
return encryptList; return;
int progressValue = 0; int progressValue = 0;
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory(); string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
foreach (var bundleInfo in buildMapContext.BundleInfos) foreach (var bundleInfo in buildMapContext.BundleInfos)
{ {
if (encryptionServices.Check(bundleInfo.BundleName)) bundleInfo.LoadMethod = EBundleLoadMethod.Normal;
EncryptFileInfo fileInfo = new EncryptFileInfo();
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)
{ {
UnityEngine.Debug.LogWarning($"Encryption not support raw file : {bundleInfo.BundleName}"); UnityEngine.Debug.LogWarning($"Encryption not support raw file : {bundleInfo.BundleName}");
continue; continue;
} }
encryptList.Add(bundleInfo.BundleName); string filePath = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}.encrypt";
FileUtility.CreateFile(filePath, encryptResult.EncryptedData);
// 注意:通过判断文件合法性,规避重复加密一个文件 bundleInfo.EncryptedFilePath = filePath;
string filePath = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}"; bundleInfo.LoadMethod = encryptResult.LoadMethod;
byte[] fileData = File.ReadAllBytes(filePath); BuildRunner.Log($"Bundle文件加密完成{filePath}");
if (EditorTools.CheckBundleFileValid(fileData))
{
byte[] bytes = encryptionServices.Encrypt(fileData);
File.WriteAllBytes(filePath, bytes);
BuildRunner.Log($"文件加密完成:{filePath}");
}
} }
// 进度条 // 进度条
EditorTools.DisplayProgressBar("加密资源包", ++progressValue, buildMapContext.BundleInfos.Count); EditorTools.DisplayProgressBar("加密资源包", ++progressValue, buildMapContext.BundleInfos.Count);
} }
EditorTools.ClearProgressBar(); EditorTools.ClearProgressBar();
if(encryptList.Count == 0)
UnityEngine.Debug.LogWarning($"没有发现需要加密的文件!");
return encryptList;
} }
} }
} }

View File

@@ -13,7 +13,7 @@ namespace YooAsset.Editor
void IBuildTask.Run(BuildContext context) void IBuildTask.Run(BuildContext context)
{ {
var buildParametersContext = context.GetContextObject<BuildParametersContext>(); var buildParametersContext = context.GetContextObject<BuildParametersContext>();
var buildMapContext = BuildMapCreater.CreateBuildMap(buildParametersContext.Parameters.BuildMode, buildParametersContext.Parameters.BuildPackage); var buildMapContext = BuildMapCreater.CreateBuildMap(buildParametersContext.Parameters.BuildMode, buildParametersContext.Parameters.PackageName);
context.SetContextObject(buildMapContext); context.SetContextObject(buildMapContext);
BuildRunner.Log("构建内容准备完毕!"); BuildRunner.Log("构建内容准备完毕!");

View File

@@ -19,8 +19,10 @@ namespace YooAsset.Editor
// 检测构建参数合法性 // 检测构建参数合法性
if (buildParameters.BuildTarget == BuildTarget.NoTarget) if (buildParameters.BuildTarget == BuildTarget.NoTarget)
throw new Exception("请选择目标平台"); throw new Exception("请选择目标平台");
if (string.IsNullOrEmpty(buildParameters.BuildPackage)) if (string.IsNullOrEmpty(buildParameters.PackageName))
throw new Exception("包裹名称不能为空"); throw new Exception("包裹名称不能为空");
if(string.IsNullOrEmpty(buildParameters.PackageVersion))
throw new Exception("包裹版本不能为空");
if (buildParameters.BuildMode != EBuildMode.SimulateBuild) if (buildParameters.BuildMode != EBuildMode.SimulateBuild)
{ {
@@ -40,6 +42,11 @@ namespace YooAsset.Editor
throw new Exception("首包资源标签不能为空!"); throw new Exception("首包资源标签不能为空!");
} }
// 检测包裹输出目录是否存在
string packageOutputDirectory = buildParametersContext.GetPackageOutputDirectory();
if (Directory.Exists(packageOutputDirectory))
throw new Exception($"本次构建的补丁目录已经存在:{packageOutputDirectory}");
// 保存改动的资源 // 保存改动的资源
AssetDatabase.SaveAssets(); AssetDatabase.SaveAssets();
} }
@@ -47,7 +54,7 @@ namespace YooAsset.Editor
if (buildParameters.BuildMode == EBuildMode.ForceRebuild) if (buildParameters.BuildMode == EBuildMode.ForceRebuild)
{ {
// 删除平台总目录 // 删除平台总目录
string platformDirectory = $"{buildParameters.OutputRoot}/{buildParameters.BuildPackage}/{buildParameters.BuildTarget}"; string platformDirectory = $"{buildParameters.OutputRoot}/{buildParameters.PackageName}/{buildParameters.BuildTarget}";
if (EditorTools.DeleteDirectory(platformDirectory)) if (EditorTools.DeleteDirectory(platformDirectory))
{ {
BuildRunner.Log($"删除平台总目录:{platformDirectory}"); BuildRunner.Log($"删除平台总目录:{platformDirectory}");

View File

@@ -0,0 +1,118 @@
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
namespace YooAsset.Editor
{
[TaskAttribute("更新构建信息")]
public class TaskUpdateBuildInfo : 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.BundleInfos)
{
// NOTE检测路径长度不要超过260字符。
string filePath = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}";
if (filePath.Length >= 260)
throw new Exception($"The output bundle name is too long {filePath.Length} chars : {filePath}");
}
// 2.更新构建输出的文件路径
foreach (var bundleInfo in buildMapContext.BundleInfos)
{
if (bundleInfo.IsEncryptedFile)
bundleInfo.PatchInfo.BuildOutputFilePath = bundleInfo.EncryptedFilePath;
else
bundleInfo.PatchInfo.BuildOutputFilePath = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}";
}
// 3.更新文件其它信息
foreach (var bundleInfo in buildMapContext.BundleInfos)
{
string buildOutputFilePath = bundleInfo.PatchInfo.BuildOutputFilePath;
bundleInfo.PatchInfo.ContentHash = GetBundleContentHash(bundleInfo, context);
bundleInfo.PatchInfo.PatchFileHash = GetBundleFileHash(buildOutputFilePath, buildParametersContext);
bundleInfo.PatchInfo.PatchFileCRC = GetBundleFileCRC(buildOutputFilePath, buildParametersContext);
bundleInfo.PatchInfo.PatchFileSize = GetBundleFileSize(buildOutputFilePath, buildParametersContext);
}
// 4.更新补丁包输出的文件路径
foreach (var bundleInfo in buildMapContext.BundleInfos)
{
string patchFileName = PatchManifestTools.CreateBundleFileName(outputNameStyle, bundleInfo.BundleName, bundleInfo.PatchInfo.PatchFileHash, bundleInfo.IsRawFile);
bundleInfo.PatchInfo.PatchOutputFilePath = $"{packageOutputDirectory}/{patchFileName}";
}
}
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.PatchInfo.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,5 +1,5 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: 223f217ed81460541b5ea7eb7a7d82a4 guid: 4882f54fbf0bcb04680fb581deae4889
MonoImporter: MonoImporter:
externalObjects: {} externalObjects: {}
serializedVersion: 2 serializedVersion: 2

View File

@@ -62,6 +62,7 @@ namespace YooAsset.Editor
} }
// 4. 验证Asset // 4. 验证Asset
/*
bool isPass = true; bool isPass = true;
var buildMode = buildParametersContext.Parameters.BuildMode; var buildMode = buildParametersContext.Parameters.BuildMode;
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild) if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
@@ -98,6 +99,7 @@ namespace YooAsset.Editor
throw new Exception("构建结果验证没有通过,请参考警告日志!"); throw new Exception("构建结果验证没有通过,请参考警告日志!");
} }
} }
*/
BuildRunner.Log("构建结果验证成功!"); BuildRunner.Log("构建结果验证成功!");
} }

View File

@@ -7,23 +7,13 @@ namespace YooAsset.Editor
public enum EOutputNameStyle public enum EOutputNameStyle
{ {
/// <summary> /// <summary>
/// 000000000000000f000000000000000 /// 哈希值名称
/// </summary> /// </summary>
HashName = 1, HashName = 1,
/// <summary> /// <summary>
/// 000000000000000f000000000000000.bundle /// 资源包名称 + 哈希值名称
/// </summary> /// </summary>
HashName_Extension = 2, BundleName_HashName = 4,
/// <summary>
/// bundle_name_000000000000000f000000000000000
/// </summary>
BundleName_HashName = 3,
/// <summary>
/// bundle_name_000000000000000f000000000000000.bundle
/// </summary>
BundleName_HashName_Extension = 4,
} }
} }

View File

@@ -1,18 +0,0 @@

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

@@ -240,13 +240,15 @@ namespace YooAsset.Editor
return false; return false;
// 忽略Unity无法识别的无效文件 // 忽略Unity无法识别的无效文件
/* // 注意:只对非原生文件收集器处理
if (type == typeof(UnityEditor.DefaultAsset)) if(PackRuleName != nameof(PackRawFile))
{ {
UnityEngine.Debug.LogWarning($"Cannot pack default asset : {assetPath}"); if (type == typeof(UnityEditor.DefaultAsset))
return false; {
UnityEngine.Debug.LogWarning($"Cannot pack default asset : {assetPath}");
return false;
}
} }
*/
string fileExtension = System.IO.Path.GetExtension(assetPath); string fileExtension = System.IO.Path.GetExtension(assetPath);
if (IsIgnoreFile(fileExtension)) if (IsIgnoreFile(fileExtension))
@@ -291,12 +293,15 @@ namespace YooAsset.Editor
// 根据规则设置获取资源包名称 // 根据规则设置获取资源包名称
IPackRule packRuleInstance = AssetBundleCollectorSettingData.GetPackRuleInstance(PackRuleName); IPackRule packRuleInstance = AssetBundleCollectorSettingData.GetPackRuleInstance(PackRuleName);
string bundleName = packRuleInstance.GetBundleName(new PackRuleData(assetPath, CollectPath, group.GroupName)); string bundleName = packRuleInstance.GetBundleName(new PackRuleData(assetPath, CollectPath, group.GroupName));
return EditorTools.GetRegularPath(bundleName).ToLower(); if(YooAssetSettingsData.Setting.RegularBundleName)
return EditorTools.GetRegularPath(bundleName).Replace('/', '_').Replace('.', '_').ToLower();
else
return EditorTools.GetRegularPath(bundleName).ToLower();
} }
private List<string> GetAssetTags(AssetBundleCollectorGroup group) private List<string> GetAssetTags(AssetBundleCollectorGroup group)
{ {
List<string> tags = StringUtility.StringToStringList(group.AssetTags, ';'); List<string> tags = EditorTools.StringToStringList(group.AssetTags, ';');
List<string> temper = StringUtility.StringToStringList(AssetTags, ';'); List<string> temper = EditorTools.StringToStringList(AssetTags, ';');
tags.AddRange(temper); tags.AddRange(temper);
return tags; return tags;
} }

View File

@@ -10,13 +10,14 @@ namespace YooAsset.Editor
{ {
public class AssetBundleCollectorConfig public class AssetBundleCollectorConfig
{ {
public const string ConfigVersion = "2.1"; public const string ConfigVersion = "2.2";
public const string XmlVersion = "Version"; public const string XmlVersion = "Version";
public const string XmlCommon = "Common"; public const string XmlCommon = "Common";
public const string XmlEnableAddressable = "AutoAddressable"; public const string XmlEnableAddressable = "AutoAddressable";
public const string XmlUniqueBundleName = "UniqueBundleName"; public const string XmlUniqueBundleName = "UniqueBundleName";
public const string XmlShowPackageView = "ShowPackageView"; public const string XmlShowPackageView = "ShowPackageView";
public const string XmlShowEditorAlias = "ShowEditorAlias";
public const string XmlPackage = "Package"; public const string XmlPackage = "Package";
public const string XmlPackageName = "PackageName"; public const string XmlPackageName = "PackageName";
@@ -65,6 +66,7 @@ namespace YooAsset.Editor
bool enableAddressable = false; bool enableAddressable = false;
bool uniqueBundleName = false; bool uniqueBundleName = false;
bool showPackageView = false; bool showPackageView = false;
bool showEditorAlias = false;
var commonNodeList = root.GetElementsByTagName(XmlCommon); var commonNodeList = root.GetElementsByTagName(XmlCommon);
if (commonNodeList.Count > 0) if (commonNodeList.Count > 0)
{ {
@@ -75,10 +77,13 @@ namespace YooAsset.Editor
throw new Exception($"Not found attribute {XmlUniqueBundleName} in {XmlCommon}"); throw new Exception($"Not found attribute {XmlUniqueBundleName} in {XmlCommon}");
if (commonElement.HasAttribute(XmlShowPackageView) == false) if (commonElement.HasAttribute(XmlShowPackageView) == false)
throw new Exception($"Not found attribute {XmlShowPackageView} in {XmlCommon}"); 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; enableAddressable = commonElement.GetAttribute(XmlEnableAddressable) == "True" ? true : false;
uniqueBundleName = commonElement.GetAttribute(XmlUniqueBundleName) == "True" ? true : false; uniqueBundleName = commonElement.GetAttribute(XmlUniqueBundleName) == "True" ? true : false;
showPackageView = commonElement.GetAttribute(XmlShowPackageView) == "True" ? true : false; showPackageView = commonElement.GetAttribute(XmlShowPackageView) == "True" ? true : false;
showEditorAlias = commonElement.GetAttribute(XmlShowEditorAlias) == "True" ? true : false;
} }
// 读取包裹配置 // 读取包裹配置
@@ -138,7 +143,7 @@ namespace YooAsset.Editor
AssetBundleCollector collector = new AssetBundleCollector(); AssetBundleCollector collector = new AssetBundleCollector();
collector.CollectPath = collectorElement.GetAttribute(XmlCollectPath); collector.CollectPath = collectorElement.GetAttribute(XmlCollectPath);
collector.CollectorGUID = collectorElement.GetAttribute(XmlCollectorGUID); collector.CollectorGUID = collectorElement.GetAttribute(XmlCollectorGUID);
collector.CollectorType = StringUtility.NameToEnum<ECollectorType>(collectorElement.GetAttribute(XmlCollectorType)); collector.CollectorType = EditorTools.NameToEnum<ECollectorType>(collectorElement.GetAttribute(XmlCollectorType));
collector.AddressRuleName = collectorElement.GetAttribute(XmlAddressRule); collector.AddressRuleName = collectorElement.GetAttribute(XmlAddressRule);
collector.PackRuleName = collectorElement.GetAttribute(XmlPackRule); collector.PackRuleName = collectorElement.GetAttribute(XmlPackRule);
collector.FilterRuleName = collectorElement.GetAttribute(XmlFilterRule); collector.FilterRuleName = collectorElement.GetAttribute(XmlFilterRule);
@@ -153,6 +158,7 @@ namespace YooAsset.Editor
AssetBundleCollectorSettingData.Setting.EnableAddressable = enableAddressable; AssetBundleCollectorSettingData.Setting.EnableAddressable = enableAddressable;
AssetBundleCollectorSettingData.Setting.UniqueBundleName = uniqueBundleName; AssetBundleCollectorSettingData.Setting.UniqueBundleName = uniqueBundleName;
AssetBundleCollectorSettingData.Setting.ShowPackageView = showPackageView; AssetBundleCollectorSettingData.Setting.ShowPackageView = showPackageView;
AssetBundleCollectorSettingData.Setting.ShowEditorAlias = showEditorAlias;
AssetBundleCollectorSettingData.Setting.Packages.AddRange(packages); AssetBundleCollectorSettingData.Setting.Packages.AddRange(packages);
AssetBundleCollectorSettingData.SaveFile(); AssetBundleCollectorSettingData.SaveFile();
Debug.Log($"导入配置完毕!"); Debug.Log($"导入配置完毕!");
@@ -183,6 +189,7 @@ namespace YooAsset.Editor
commonElement.SetAttribute(XmlEnableAddressable, AssetBundleCollectorSettingData.Setting.EnableAddressable.ToString()); commonElement.SetAttribute(XmlEnableAddressable, AssetBundleCollectorSettingData.Setting.EnableAddressable.ToString());
commonElement.SetAttribute(XmlUniqueBundleName, AssetBundleCollectorSettingData.Setting.UniqueBundleName.ToString()); commonElement.SetAttribute(XmlUniqueBundleName, AssetBundleCollectorSettingData.Setting.UniqueBundleName.ToString());
commonElement.SetAttribute(XmlShowPackageView, AssetBundleCollectorSettingData.Setting.ShowPackageView.ToString()); commonElement.SetAttribute(XmlShowPackageView, AssetBundleCollectorSettingData.Setting.ShowPackageView.ToString());
commonElement.SetAttribute(XmlShowEditorAlias, AssetBundleCollectorSettingData.Setting.ShowEditorAlias.ToString());
root.AppendChild(commonElement); root.AppendChild(commonElement);
// 设置Package配置 // 设置Package配置
@@ -296,6 +303,23 @@ namespace YooAsset.Editor
return UpdateXmlConfig(xmlDoc); 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);
}
return false; return false;
} }
} }

View File

@@ -102,7 +102,7 @@ namespace YooAsset.Editor
HashSet<string> result = new HashSet<string>(); HashSet<string> result = new HashSet<string>();
foreach (var group in Groups) foreach (var group in Groups)
{ {
List<string> groupTags = StringUtility.StringToStringList(group.AssetTags, ';'); List<string> groupTags = EditorTools.StringToStringList(group.AssetTags, ';');
foreach (var tag in groupTags) foreach (var tag in groupTags)
{ {
if (result.Contains(tag) == false) if (result.Contains(tag) == false)
@@ -111,7 +111,7 @@ namespace YooAsset.Editor
foreach (var collector in group.Collectors) foreach (var collector in group.Collectors)
{ {
List<string> collectorTags = StringUtility.StringToStringList(collector.AssetTags, ';'); List<string> collectorTags = EditorTools.StringToStringList(collector.AssetTags, ';');
foreach (var tag in collectorTags) foreach (var tag in collectorTags)
{ {
if (result.Contains(tag) == false) if (result.Contains(tag) == false)

View File

@@ -23,6 +23,12 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public bool UniqueBundleName = false; public bool UniqueBundleName = false;
/// <summary>
/// 是否显示编辑器别名
/// </summary>
public bool ShowEditorAlias = false;
/// <summary> /// <summary>
/// 包裹列表 /// 包裹列表
/// </summary> /// </summary>

View File

@@ -38,92 +38,6 @@ namespace YooAsset.Editor
} }
} }
public static List<string> GetActiveRuleNames()
{
if (_setting == null)
LoadSettingData();
List<string> names = new List<string>();
foreach (var pair in _cacheActiveRuleTypes)
{
names.Add(pair.Key);
}
return names;
}
public static List<string> GetAddressRuleNames()
{
if (_setting == null)
LoadSettingData();
List<string> names = new List<string>();
foreach (var pair in _cacheAddressRuleTypes)
{
names.Add(pair.Key);
}
return names;
}
public static List<string> GetPackRuleNames()
{
if (_setting == null)
LoadSettingData();
List<string> names = new List<string>();
foreach (var pair in _cachePackRuleTypes)
{
names.Add(pair.Key);
}
return names;
}
public static List<string> GetFilterRuleNames()
{
if (_setting == null)
LoadSettingData();
List<string> names = new List<string>();
foreach (var pair in _cacheFilterRuleTypes)
{
names.Add(pair.Key);
}
return names;
}
public static bool HasActiveRuleName(string ruleName)
{
foreach (var pair in _cacheActiveRuleTypes)
{
if (pair.Key == ruleName)
return true;
}
return false;
}
public static bool HasAddressRuleName(string ruleName)
{
foreach (var pair in _cacheAddressRuleTypes)
{
if (pair.Key == ruleName)
return true;
}
return false;
}
public static bool HasPackRuleName(string ruleName)
{
foreach (var pair in _cachePackRuleTypes)
{
if (pair.Key == ruleName)
return true;
}
return false;
}
public static bool HasFilterRuleName(string ruleName)
{
foreach (var pair in _cacheFilterRuleTypes)
{
if (pair.Key == ruleName)
return true;
}
return false;
}
/// <summary> /// <summary>
/// 加载配置文件 /// 加载配置文件
/// </summary> /// </summary>
@@ -146,6 +60,7 @@ namespace YooAsset.Editor
typeof(PackCollector), typeof(PackCollector),
typeof(PackGroup), typeof(PackGroup),
typeof(PackRawFile), typeof(PackRawFile),
typeof(PackShaderVariants)
}; };
var customTypes = EditorTools.GetAssignableTypes(typeof(IPackRule)); var customTypes = EditorTools.GetAssignableTypes(typeof(IPackRule));
@@ -266,7 +181,92 @@ namespace YooAsset.Editor
SaveFile(); SaveFile();
} }
// 实例类相关 public static List<RuleDisplayName> GetActiveRuleNames()
{
if (_setting == null)
LoadSettingData();
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()
{
if (_setting == null)
LoadSettingData();
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()
{
if (_setting == null)
LoadSettingData();
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()
{
if (_setting == null)
LoadSettingData();
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 = EditorAttribute.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) public static IActiveRule GetActiveRuleInstance(string ruleName)
{ {
if (_cacheActiveRuleInstance.TryGetValue(ruleName, out IActiveRule instance)) if (_cacheActiveRuleInstance.TryGetValue(ruleName, out IActiveRule instance))
@@ -352,6 +352,11 @@ namespace YooAsset.Editor
Setting.UniqueBundleName = uniqueBundleName; Setting.UniqueBundleName = uniqueBundleName;
IsDirty = true; IsDirty = true;
} }
public static void ModifyShowEditorAlias(bool showAlias)
{
Setting.ShowEditorAlias = showAlias;
IsDirty = true;
}
// 资源包裹编辑相关 // 资源包裹编辑相关
public static AssetBundleCollectorPackage CreatePackage(string packageName) public static AssetBundleCollectorPackage CreatePackage(string packageName)

View File

@@ -20,14 +20,15 @@ namespace YooAsset.Editor
private Button _saveButton; private Button _saveButton;
private List<string> _collectorTypeList; private List<string> _collectorTypeList;
private List<string> _activeRuleList; private List<RuleDisplayName> _activeRuleList;
private List<string> _addressRuleList; private List<RuleDisplayName> _addressRuleList;
private List<string> _packRuleList; private List<RuleDisplayName> _packRuleList;
private List<string> _filterRuleList; private List<RuleDisplayName> _filterRuleList;
private Toggle _showPackageToogle; private Toggle _showPackageToogle;
private Toggle _enableAddressableToogle; private Toggle _enableAddressableToogle;
private Toggle _uniqueBundleNameToogle; private Toggle _uniqueBundleNameToogle;
private Toggle _showEditorAliasToggle;
private VisualElement _packageContainer; private VisualElement _packageContainer;
private ListView _packageListView; private ListView _packageListView;
@@ -42,7 +43,7 @@ namespace YooAsset.Editor
private VisualElement _collectorContainer; private VisualElement _collectorContainer;
private ScrollView _collectorScrollView; private ScrollView _collectorScrollView;
private PopupField<string> _activeRulePopupField; private PopupField<RuleDisplayName> _activeRulePopupField;
private int _lastModifyPackageIndex = 0; private int _lastModifyPackageIndex = 0;
private int _lastModifyGroupIndex = 0; private int _lastModifyGroupIndex = 0;
@@ -95,6 +96,13 @@ namespace YooAsset.Editor
RefreshWindow(); RefreshWindow();
}); });
_showEditorAliasToggle = root.Q<Toggle>("ShowEditorAlias");
_showEditorAliasToggle.RegisterValueChangedCallback(evt =>
{
AssetBundleCollectorSettingData.ModifyShowEditorAlias(evt.newValue);
RefreshWindow();
});
// 配置修复按钮 // 配置修复按钮
var fixBtn = root.Q<Button>("FixButton"); var fixBtn = root.Q<Button>("FixButton");
fixBtn.clicked += FixBtn_clicked; fixBtn.clicked += FixBtn_clicked;
@@ -187,6 +195,7 @@ namespace YooAsset.Editor
{ {
selectGroup.GroupName = evt.newValue; selectGroup.GroupName = evt.newValue;
AssetBundleCollectorSettingData.ModifyGroup(selectPackage, selectGroup); AssetBundleCollectorSettingData.ModifyGroup(selectPackage, selectGroup);
FillGroupViewData();
} }
}); });
@@ -200,6 +209,7 @@ namespace YooAsset.Editor
{ {
selectGroup.GroupDesc = evt.newValue; selectGroup.GroupDesc = evt.newValue;
AssetBundleCollectorSettingData.ModifyGroup(selectPackage, selectGroup); AssetBundleCollectorSettingData.ModifyGroup(selectPackage, selectGroup);
FillGroupViewData();
} }
}); });
@@ -234,21 +244,23 @@ namespace YooAsset.Editor
// 分组激活规则 // 分组激活规则
var activeRuleContainer = root.Q("ActiveRuleContainer"); var activeRuleContainer = root.Q("ActiveRuleContainer");
{ {
_activeRulePopupField = new PopupField<string>("Active Rule", _activeRuleList, 0); _activeRulePopupField = new PopupField<RuleDisplayName>("Active Rule", _activeRuleList, 0);
_activeRulePopupField.name = "ActiveRuleMaskField"; _activeRulePopupField.name = "ActiveRuleMaskField";
_activeRulePopupField.style.unityTextAlign = TextAnchor.MiddleLeft; _activeRulePopupField.style.unityTextAlign = TextAnchor.MiddleLeft;
activeRuleContainer.Add(_activeRulePopupField); _activeRulePopupField.formatListItemCallback = FormatListItemCallback;
_activeRulePopupField.formatSelectedValueCallback = FormatSelectedValueCallback;
_activeRulePopupField.RegisterValueChangedCallback(evt => _activeRulePopupField.RegisterValueChangedCallback(evt =>
{ {
var selectPackage = _packageListView.selectedItem as AssetBundleCollectorPackage; var selectPackage = _packageListView.selectedItem as AssetBundleCollectorPackage;
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup; var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectPackage != null && selectGroup != null) if (selectPackage != null && selectGroup != null)
{ {
selectGroup.ActiveRuleName = evt.newValue; selectGroup.ActiveRuleName = evt.newValue.ClassName;
AssetBundleCollectorSettingData.ModifyGroup(selectPackage, selectGroup); AssetBundleCollectorSettingData.ModifyGroup(selectPackage, selectGroup);
FillGroupViewData(); FillGroupViewData();
} }
}); });
activeRuleContainer.Add(_activeRulePopupField);
} }
// 刷新窗体 // 刷新窗体
@@ -288,6 +300,9 @@ namespace YooAsset.Editor
{ {
_showPackageToogle.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.ShowPackageView); _showPackageToogle.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.ShowPackageView);
_enableAddressableToogle.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.EnableAddressable); _enableAddressableToogle.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.EnableAddressable);
_uniqueBundleNameToogle.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.UniqueBundleName);
_showEditorAliasToggle.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.ShowEditorAlias);
_groupContainer.visible = false; _groupContainer.visible = false;
_collectorContainer.visible = false; _collectorContainer.visible = false;
@@ -319,6 +334,20 @@ namespace YooAsset.Editor
{ {
AssetBundleCollectorSettingData.SaveFile(); 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() private void FillPackageViewData()
@@ -332,7 +361,7 @@ namespace YooAsset.Editor
{ {
_packageListView.selectedIndex = _lastModifyPackageIndex; _packageListView.selectedIndex = _lastModifyPackageIndex;
} }
if (_showPackageToogle.value) if (_showPackageToogle.value)
_packageContainer.style.display = DisplayStyle.Flex; _packageContainer.style.display = DisplayStyle.Flex;
else else
@@ -408,7 +437,7 @@ namespace YooAsset.Editor
_groupListView.itemsSource = selectPackage.Groups; _groupListView.itemsSource = selectPackage.Groups;
_groupListView.Rebuild(); _groupListView.Rebuild();
if(_lastModifyGroupIndex >=0 && _lastModifyGroupIndex < _groupListView.itemsSource.Count) if (_lastModifyGroupIndex >= 0 && _lastModifyGroupIndex < _groupListView.itemsSource.Count)
{ {
_groupListView.selectedIndex = _lastModifyGroupIndex; _groupListView.selectedIndex = _lastModifyGroupIndex;
} }
@@ -458,7 +487,7 @@ namespace YooAsset.Editor
_collectorContainer.visible = true; _collectorContainer.visible = true;
_lastModifyGroupIndex = _groupListView.selectedIndex; _lastModifyGroupIndex = _groupListView.selectedIndex;
_activeRulePopupField.SetValueWithoutNotify(selectGroup.ActiveRuleName); _activeRulePopupField.SetValueWithoutNotify(GetActiveRuleIndex(selectGroup.ActiveRuleName));
_groupNameTxt.SetValueWithoutNotify(selectGroup.GroupName); _groupNameTxt.SetValueWithoutNotify(selectGroup.GroupName);
_groupDescTxt.SetValueWithoutNotify(selectGroup.GroupDesc); _groupDescTxt.SetValueWithoutNotify(selectGroup.GroupDesc);
_groupAssetTagsTxt.SetValueWithoutNotify(selectGroup.AssetTags); _groupAssetTagsTxt.SetValueWithoutNotify(selectGroup.AssetTags);
@@ -562,21 +591,21 @@ namespace YooAsset.Editor
} }
if (_enableAddressableToogle.value) if (_enableAddressableToogle.value)
{ {
var popupField = new PopupField<string>(_addressRuleList, 0); var popupField = new PopupField<RuleDisplayName>(_addressRuleList, 0);
popupField.name = "PopupField1"; popupField.name = "PopupField1";
popupField.style.unityTextAlign = TextAnchor.MiddleLeft; popupField.style.unityTextAlign = TextAnchor.MiddleLeft;
popupField.style.width = 200; popupField.style.width = 200;
elementBottom.Add(popupField); elementBottom.Add(popupField);
} }
{ {
var popupField = new PopupField<string>(_packRuleList, 0); var popupField = new PopupField<RuleDisplayName>(_packRuleList, 0);
popupField.name = "PopupField2"; popupField.name = "PopupField2";
popupField.style.unityTextAlign = TextAnchor.MiddleLeft; popupField.style.unityTextAlign = TextAnchor.MiddleLeft;
popupField.style.width = 150; popupField.style.width = 230;
elementBottom.Add(popupField); elementBottom.Add(popupField);
} }
{ {
var popupField = new PopupField<string>(_filterRuleList, 0); var popupField = new PopupField<RuleDisplayName>(_filterRuleList, 0);
popupField.name = "PopupField3"; popupField.name = "PopupField3";
popupField.style.unityTextAlign = TextAnchor.MiddleLeft; popupField.style.unityTextAlign = TextAnchor.MiddleLeft;
popupField.style.width = 150; popupField.style.width = 150;
@@ -665,7 +694,7 @@ namespace YooAsset.Editor
popupField0.index = GetCollectorTypeIndex(collector.CollectorType.ToString()); popupField0.index = GetCollectorTypeIndex(collector.CollectorType.ToString());
popupField0.RegisterValueChangedCallback(evt => popupField0.RegisterValueChangedCallback(evt =>
{ {
collector.CollectorType = StringUtility.NameToEnum<ECollectorType>(evt.newValue); collector.CollectorType = EditorTools.NameToEnum<ECollectorType>(evt.newValue);
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector); AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value) if (foldout.value)
{ {
@@ -674,13 +703,15 @@ namespace YooAsset.Editor
}); });
// Address Rule // Address Rule
var popupField1 = element.Q<PopupField<string>>("PopupField1"); var popupField1 = element.Q<PopupField<RuleDisplayName>>("PopupField1");
if (popupField1 != null) if (popupField1 != null)
{ {
popupField1.index = GetAddressRuleIndex(collector.AddressRuleName); popupField1.index = GetAddressRuleIndex(collector.AddressRuleName);
popupField1.formatListItemCallback = FormatListItemCallback;
popupField1.formatSelectedValueCallback = FormatSelectedValueCallback;
popupField1.RegisterValueChangedCallback(evt => popupField1.RegisterValueChangedCallback(evt =>
{ {
collector.AddressRuleName = evt.newValue; collector.AddressRuleName = evt.newValue.ClassName;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector); AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value) if (foldout.value)
{ {
@@ -690,11 +721,13 @@ namespace YooAsset.Editor
} }
// Pack Rule // Pack Rule
var popupField2 = element.Q<PopupField<string>>("PopupField2"); var popupField2 = element.Q<PopupField<RuleDisplayName>>("PopupField2");
popupField2.index = GetPackRuleIndex(collector.PackRuleName); popupField2.index = GetPackRuleIndex(collector.PackRuleName);
popupField2.formatListItemCallback = FormatListItemCallback;
popupField2.formatSelectedValueCallback = FormatSelectedValueCallback;
popupField2.RegisterValueChangedCallback(evt => popupField2.RegisterValueChangedCallback(evt =>
{ {
collector.PackRuleName = evt.newValue; collector.PackRuleName = evt.newValue.ClassName;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector); AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value) if (foldout.value)
{ {
@@ -703,11 +736,13 @@ namespace YooAsset.Editor
}); });
// Filter Rule // Filter Rule
var popupField3 = element.Q<PopupField<string>>("PopupField3"); var popupField3 = element.Q<PopupField<RuleDisplayName>>("PopupField3");
popupField3.index = GetFilterRuleIndex(collector.FilterRuleName); popupField3.index = GetFilterRuleIndex(collector.FilterRuleName);
popupField3.formatListItemCallback = FormatListItemCallback;
popupField3.formatSelectedValueCallback = FormatSelectedValueCallback;
popupField3.RegisterValueChangedCallback(evt => popupField3.RegisterValueChangedCallback(evt =>
{ {
collector.FilterRuleName = evt.newValue; collector.FilterRuleName = evt.newValue.ClassName;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector); AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value) if (foldout.value)
{ {
@@ -813,7 +848,7 @@ namespace YooAsset.Editor
{ {
for (int i = 0; i < _addressRuleList.Count; i++) for (int i = 0; i < _addressRuleList.Count; i++)
{ {
if (_addressRuleList[i] == ruleName) if (_addressRuleList[i].ClassName == ruleName)
return i; return i;
} }
return 0; return 0;
@@ -822,7 +857,7 @@ namespace YooAsset.Editor
{ {
for (int i = 0; i < _packRuleList.Count; i++) for (int i = 0; i < _packRuleList.Count; i++)
{ {
if (_packRuleList[i] == ruleName) if (_packRuleList[i].ClassName == ruleName)
return i; return i;
} }
return 0; return 0;
@@ -831,11 +866,20 @@ namespace YooAsset.Editor
{ {
for (int i = 0; i < _filterRuleList.Count; i++) for (int i = 0; i < _filterRuleList.Count; i++)
{ {
if (_filterRuleList[i] == ruleName) if (_filterRuleList[i].ClassName == ruleName)
return i; return i;
} }
return 0; 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 #endif

View File

@@ -1,4 +1,4 @@
<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">
<uie:Toolbar name="Toolbar" style="display: flex; flex-direction: row-reverse;"> <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="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="ExportButton" style="width: 50px; background-color: rgb(56, 147, 58);" />
@@ -7,6 +7,7 @@
</uie:Toolbar> </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: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 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="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:Toggle label="Unique Bundle Name" name="UniqueBundleName" style="width: 196px; -unity-text-align: middle-left;" />
</ui:VisualElement> </ui:VisualElement>

View File

@@ -50,13 +50,5 @@ namespace YooAsset.Editor
AssetTags = assetTags; AssetTags = assetTags;
IsRawAsset = isRawAsset; IsRawAsset = isRawAsset;
} }
/// <summary>
/// 资源包名称追加包裹名
/// </summary>
public void BundleNameAppendPackageName(string packageName)
{
BundleName = $"{packageName.ToLower()}_{BundleName}";
}
} }
} }

View File

@@ -36,14 +36,6 @@ namespace YooAsset.Editor
public void SetCollectAssets(List<CollectAssetInfo> collectAssets) public void SetCollectAssets(List<CollectAssetInfo> collectAssets)
{ {
CollectAssets = collectAssets; CollectAssets = collectAssets;
if (UniqueBundleName)
{
foreach (var collectAsset in CollectAssets)
{
collectAsset.BundleNameAppendPackageName(PackageName);
}
}
} }
} }
} }

View File

@@ -1,9 +1,7 @@
 
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
/// <summary> [DisplayName("启用分组")]
/// 启用分组
/// </summary>
public class EnableGroup : IActiveRule public class EnableGroup : IActiveRule
{ {
public bool IsActiveGroup() public bool IsActiveGroup()
@@ -12,9 +10,7 @@ namespace YooAsset.Editor
} }
} }
/// <summary> [DisplayName("禁用分组")]
/// 禁用分组
/// </summary>
public class DisableGroup : IActiveRule public class DisableGroup : IActiveRule
{ {
public bool IsActiveGroup() public bool IsActiveGroup()

View File

@@ -2,9 +2,7 @@
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
/// <summary> [DisplayName("以文件名称为定位地址")]
/// 以文件名为定位地址
/// </summary>
public class AddressByFileName : IAddressRule public class AddressByFileName : IAddressRule
{ {
string IAddressRule.GetAssetAddress(AddressRuleData data) string IAddressRule.GetAssetAddress(AddressRuleData data)
@@ -13,9 +11,7 @@ namespace YooAsset.Editor
} }
} }
/// <summary> [DisplayName("以分组名称+文件名称为定位地址")]
/// 以组名+文件名为定位地址
/// </summary>
public class AddressByGroupAndFileName : IAddressRule public class AddressByGroupAndFileName : IAddressRule
{ {
string IAddressRule.GetAssetAddress(AddressRuleData data) string IAddressRule.GetAssetAddress(AddressRuleData data)
@@ -25,9 +21,7 @@ namespace YooAsset.Editor
} }
} }
/// <summary> [DisplayName("以收集器名称+文件名称为定位地址")]
/// 以收集器名+文件名为定位地址
/// </summary>
public class AddressByCollectorAndFileName : IAddressRule public class AddressByCollectorAndFileName : IAddressRule
{ {
string IAddressRule.GetAssetAddress(AddressRuleData data) string IAddressRule.GetAssetAddress(AddressRuleData data)

View File

@@ -4,9 +4,7 @@ using System.IO;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
/// <summary> [DisplayName("收集所有资源")]
/// 收集所有资源
/// </summary>
public class CollectAll : IFilterRule public class CollectAll : IFilterRule
{ {
public bool IsCollectAsset(FilterRuleData data) public bool IsCollectAsset(FilterRuleData data)
@@ -15,9 +13,7 @@ namespace YooAsset.Editor
} }
} }
/// <summary> [DisplayName("收集场景")]
/// 只收集场景
/// </summary>
public class CollectScene : IFilterRule public class CollectScene : IFilterRule
{ {
public bool IsCollectAsset(FilterRuleData data) public bool IsCollectAsset(FilterRuleData data)
@@ -25,10 +21,8 @@ namespace YooAsset.Editor
return Path.GetExtension(data.AssetPath) == ".unity"; return Path.GetExtension(data.AssetPath) == ".unity";
} }
} }
/// <summary> [DisplayName("收集预制体")]
/// 只收集预制体
/// </summary>
public class CollectPrefab : IFilterRule public class CollectPrefab : IFilterRule
{ {
public bool IsCollectAsset(FilterRuleData data) public bool IsCollectAsset(FilterRuleData data)
@@ -37,15 +31,13 @@ namespace YooAsset.Editor
} }
} }
/// <summary> [DisplayName("收集精灵类型的纹理")]
/// 只收集精灵类型的资源
/// </summary>
public class CollectSprite : IFilterRule public class CollectSprite : IFilterRule
{ {
public bool IsCollectAsset(FilterRuleData data) public bool IsCollectAsset(FilterRuleData data)
{ {
var mainAssetType = AssetDatabase.GetMainAssetTypeAtPath(data.AssetPath); var mainAssetType = AssetDatabase.GetMainAssetTypeAtPath(data.AssetPath);
if(mainAssetType == typeof(Texture2D)) if (mainAssetType == typeof(Texture2D))
{ {
var texImporter = AssetImporter.GetAtPath(data.AssetPath) as TextureImporter; var texImporter = AssetImporter.GetAtPath(data.AssetPath) as TextureImporter;
if (texImporter != null && texImporter.textureType == TextureImporterType.Sprite) if (texImporter != null && texImporter.textureType == TextureImporterType.Sprite)
@@ -60,9 +52,7 @@ namespace YooAsset.Editor
} }
} }
/// <summary> [DisplayName("收集着色器变种集合")]
/// 只收集着色器变种收集文件
/// </summary>
public class CollectShaderVariants : IFilterRule public class CollectShaderVariants : IFilterRule
{ {
public bool IsCollectAsset(FilterRuleData data) public bool IsCollectAsset(FilterRuleData data)

View File

@@ -7,34 +7,32 @@ namespace YooAsset.Editor
/// <summary> /// <summary>
/// 以文件路径作为资源包名 /// 以文件路径作为资源包名
/// 注意:每个文件独自打资源包 /// 注意:每个文件独自打资源包
/// 例如:收集器路径为 "Assets/UIPanel" /// 例如:"Assets/UIPanel/Shop/Image/backgroud.png" --> "assets_uipanel_shop_image_backgroud.bundle"
/// 例如:"Assets/UIPanel/Shop/Image/backgroud.png" --> "assets/uipanel/shop/image/backgroud.bundle" /// 例如:"Assets/UIPanel/Shop/View/main.prefab" --> "assets_uipanel_shop_view_main.bundle"
/// 例如:"Assets/UIPanel/Shop/View/main.prefab" --> "assets/uipanel/shop/view/main.bundle"
/// </summary> /// </summary>
[DisplayName("以文件路径作为资源包名")]
public class PackSeparately : IPackRule public class PackSeparately : IPackRule
{ {
string IPackRule.GetBundleName(PackRuleData data) string IPackRule.GetBundleName(PackRuleData data)
{ {
string bundleName = StringUtility.RemoveExtension(data.AssetPath); return StringUtility.RemoveExtension(data.AssetPath);
return EditorTools.GetRegularPath(bundleName).Replace('/', '_');
} }
} }
/// <summary> /// <summary>
/// 以父类文件夹路径作为资源包名 /// 以父类文件夹路径作为资源包名
/// 注意:文件夹下所有文件打进一个资源包 /// 注意:文件夹下所有文件打进一个资源包
/// 例如:收集器路径为 "Assets/UIPanel" /// 例如:"Assets/UIPanel/Shop/Image/backgroud.png" --> "assets_uipanel_shop_image.bundle"
/// 例如:"Assets/UIPanel/Shop/Image/backgroud.png" --> "assets/uipanel/shop/image.bundle" /// 例如:"Assets/UIPanel/Shop/View/main.prefab" --> "assets_uipanel_shop_view.bundle"
/// 例如:"Assets/UIPanel/Shop/View/main.prefab" --> "assets/uipanel/shop/view.bundle"
/// </summary> /// </summary>
[DisplayName("以父类文件夹路径作为资源包名")]
public class PackDirectory : IPackRule public class PackDirectory : IPackRule
{ {
public static PackDirectory StaticPackRule = new PackDirectory(); public static PackDirectory StaticPackRule = new PackDirectory();
string IPackRule.GetBundleName(PackRuleData data) string IPackRule.GetBundleName(PackRuleData data)
{ {
string bundleName = Path.GetDirectoryName(data.AssetPath); return Path.GetDirectoryName(data.AssetPath);
return EditorTools.GetRegularPath(bundleName).Replace('/', '_');
} }
} }
@@ -42,9 +40,10 @@ namespace YooAsset.Editor
/// 以收集器路径下顶级文件夹为资源包名 /// 以收集器路径下顶级文件夹为资源包名
/// 注意:文件夹下所有文件打进一个资源包 /// 注意:文件夹下所有文件打进一个资源包
/// 例如:收集器路径为 "Assets/UIPanel" /// 例如:收集器路径为 "Assets/UIPanel"
/// 例如:"Assets/UIPanel/Shop/Image/backgroud.png" --> "assets/uipanel/shop.bundle" /// 例如:"Assets/UIPanel/Shop/Image/backgroud.png" --> "assets_uipanel_shop.bundle"
/// 例如:"Assets/UIPanel/Shop/View/main.prefab" --> "assets/uipanel/shop.bundle" /// 例如:"Assets/UIPanel/Shop/View/main.prefab" --> "assets_uipanel_shop.bundle"
/// </summary> /// </summary>
[DisplayName("以收集器路径下顶级文件夹为资源包名")]
public class PackTopDirectory : IPackRule public class PackTopDirectory : IPackRule
{ {
string IPackRule.GetBundleName(PackRuleData data) string IPackRule.GetBundleName(PackRuleData data)
@@ -57,7 +56,7 @@ namespace YooAsset.Editor
if (Path.HasExtension(splits[0])) if (Path.HasExtension(splits[0]))
throw new Exception($"Not found root directory : {assetPath}"); throw new Exception($"Not found root directory : {assetPath}");
string bundleName = $"{data.CollectPath}/{splits[0]}"; string bundleName = $"{data.CollectPath}/{splits[0]}";
return EditorTools.GetRegularPath(bundleName).Replace('/', '_'); return bundleName;
} }
else else
{ {
@@ -70,12 +69,20 @@ namespace YooAsset.Editor
/// 以收集器路径作为资源包名 /// 以收集器路径作为资源包名
/// 注意:收集的所有文件打进一个资源包 /// 注意:收集的所有文件打进一个资源包
/// </summary> /// </summary>
[DisplayName("以收集器路径作为资源包名")]
public class PackCollector : IPackRule public class PackCollector : IPackRule
{ {
string IPackRule.GetBundleName(PackRuleData data) string IPackRule.GetBundleName(PackRuleData data)
{ {
string bundleName = StringUtility.RemoveExtension(data.CollectPath); string collectPath = data.CollectPath;
return EditorTools.GetRegularPath(bundleName).Replace('/', '_'); if (AssetDatabase.IsValidFolder(collectPath))
{
return collectPath;
}
else
{
return StringUtility.RemoveExtension(collectPath);
}
} }
} }
@@ -83,6 +90,7 @@ namespace YooAsset.Editor
/// 以分组名称作为资源包名 /// 以分组名称作为资源包名
/// 注意:收集的所有文件打进一个资源包 /// 注意:收集的所有文件打进一个资源包
/// </summary> /// </summary>
[DisplayName("以分组名称作为资源包名")]
public class PackGroup : IPackRule public class PackGroup : IPackRule
{ {
string IPackRule.GetBundleName(PackRuleData data) string IPackRule.GetBundleName(PackRuleData data)
@@ -92,9 +100,10 @@ namespace YooAsset.Editor
} }
/// <summary> /// <summary>
/// 原生文件打包模式 /// 打包原生文件
/// 注意:原生文件打包支持:图片,音频,视频,文本 /// 注意:原生文件打包支持:图片,音频,视频,文本
/// </summary> /// </summary>
[DisplayName("打包原生文件")]
public class PackRawFile : IPackRule public class PackRawFile : IPackRule
{ {
string IPackRule.GetBundleName(PackRuleData data) string IPackRule.GetBundleName(PackRuleData data)
@@ -113,14 +122,14 @@ namespace YooAsset.Editor
if (depends.Length != 1) if (depends.Length != 1)
throw new Exception($"{nameof(PackRawFile)} is not support estension : {extension}"); throw new Exception($"{nameof(PackRawFile)} is not support estension : {extension}");
string bundleName = StringUtility.RemoveExtension(data.AssetPath); return data.AssetPath;
return EditorTools.GetRegularPath(bundleName).Replace('/', '_');
} }
} }
/// <summary> /// <summary>
/// 着色器变种收集文件 /// 打包着色器变种集合
/// </summary> /// </summary>
[DisplayName("打包着色器变种集合")]
public class PackShaderVariants : IPackRule public class PackShaderVariants : IPackRule
{ {
public string GetBundleName(PackRuleData data) public string GetBundleName(PackRuleData data)

View File

@@ -0,0 +1,9 @@

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

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: c4b754a3b15abc44fa2727f57721e18b guid: df712711c3830af419b7ada8fee53dda
MonoImporter: MonoImporter:
externalObjects: {} externalObjects: {}
serializedVersion: 2 serializedVersion: 2

View File

@@ -73,6 +73,10 @@ namespace YooAsset.Editor
var sampleBtn = root.Q<Button>("SampleButton"); var sampleBtn = root.Q<Button>("SampleButton");
sampleBtn.clicked += SampleBtn_onClick; sampleBtn.clicked += SampleBtn_onClick;
// 导出按钮
var exportBtn = root.Q<Button>("ExportButton");
exportBtn.clicked += ExportBtn_clicked;
// 用户列表菜单 // 用户列表菜单
_playerName = root.Q<Label>("PlayerName"); _playerName = root.Q<Label>("PlayerName");
_playerName.text = "Editor player"; _playerName.text = "Editor player";
@@ -251,6 +255,32 @@ namespace YooAsset.Editor
EditorConnection.instance.Send(RemoteDebuggerDefine.kMsgSendEditorToPlayer, data); EditorConnection.instance.Send(RemoteDebuggerDefine.kMsgSendEditorToPlayer, data);
RemoteDebuggerInRuntime.EditorRequestDebugReport(); 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.CreateFile(filePath, fileContent);
}
}
private void OnSearchKeyWordChange(ChangeEvent<string> e) private void OnSearchKeyWordChange(ChangeEvent<string> e)
{ {
_searchKeyWord = e.newValue; _searchKeyWord = e.newValue;

View File

@@ -4,6 +4,7 @@
<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="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>
<uie:Toolbar name="FrameToolbar"> <uie:Toolbar name="FrameToolbar">
<ui:SliderInt picking-mode="Ignore" label="Frame:" value="42" high-value="100" name="FrameSlider" style="flex-grow: 1;" /> <ui:SliderInt picking-mode="Ignore" label="Frame:" value="42" high-value="100" name="FrameSlider" style="flex-grow: 1;" />

View File

@@ -27,7 +27,7 @@ namespace YooAsset.Editor
_visualAsset = EditorHelper.LoadWindowUXML<DebuggerAssetListViewer>(); _visualAsset = EditorHelper.LoadWindowUXML<DebuggerAssetListViewer>();
if (_visualAsset == null) if (_visualAsset == null)
return; return;
_root = _visualAsset.CloneTree(); _root = _visualAsset.CloneTree();
_root.style.flexGrow = 1f; _root.style.flexGrow = 1f;
@@ -72,15 +72,24 @@ namespace YooAsset.Editor
} }
private List<DebugProviderInfo> FilterViewItems(DebugReport debugReport, string searchKeyWord) private List<DebugProviderInfo> FilterViewItems(DebugReport debugReport, string searchKeyWord)
{ {
var result = new List<DebugProviderInfo>(debugReport.ProviderInfos.Count); List<DebugProviderInfo> result = new List<DebugProviderInfo>(1000);
foreach (var providerInfo in debugReport.ProviderInfos) foreach (var packageData in debugReport.PackageDatas)
{ {
if (string.IsNullOrEmpty(searchKeyWord) == false) var tempList = new List<DebugProviderInfo>(packageData.ProviderInfos.Count);
foreach (var providerInfo in packageData.ProviderInfos)
{ {
if (providerInfo.AssetPath.Contains(searchKeyWord) == false) if (string.IsNullOrEmpty(searchKeyWord) == false)
continue; {
if (providerInfo.AssetPath.Contains(searchKeyWord) == false)
continue;
}
providerInfo.PackageName = packageData.PackageName;
tempList.Add(providerInfo);
} }
result.Add(providerInfo);
tempList.Sort();
result.AddRange(tempList);
} }
return result; return result;
} }
@@ -102,12 +111,22 @@ namespace YooAsset.Editor
} }
// 资源列表相关 // 顶部列表相关
private VisualElement MakeAssetListViewItem() private VisualElement MakeAssetListViewItem()
{ {
VisualElement element = new VisualElement(); VisualElement element = new VisualElement();
element.style.flexDirection = FlexDirection.Row; element.style.flexDirection = FlexDirection.Row;
{
var label = new Label();
label.name = "Label0";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
//label.style.flexGrow = 1f;
label.style.width = 150;
element.Add(label);
}
{ {
var label = new Label(); var label = new Label();
label.name = "Label1"; label.name = "Label1";
@@ -144,7 +163,7 @@ namespace YooAsset.Editor
label.style.unityTextAlign = TextAnchor.MiddleLeft; label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f; label.style.marginLeft = 3f;
//label.style.flexGrow = 1f; //label.style.flexGrow = 1f;
label.style.width = 100; label.style.width = 150;
element.Add(label); element.Add(label);
} }
@@ -154,6 +173,16 @@ namespace YooAsset.Editor
label.style.unityTextAlign = TextAnchor.MiddleLeft; label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f; label.style.marginLeft = 3f;
//label.style.flexGrow = 1f; //label.style.flexGrow = 1f;
label.style.width = 100;
element.Add(label);
}
{
var label = new Label();
label.name = "Label6";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
//label.style.flexGrow = 1f;
label.style.width = 120; label.style.width = 120;
element.Add(label); element.Add(label);
} }
@@ -165,6 +194,10 @@ namespace YooAsset.Editor
var sourceData = _assetListView.itemsSource as List<DebugProviderInfo>; var sourceData = _assetListView.itemsSource as List<DebugProviderInfo>;
var providerInfo = sourceData[index]; var providerInfo = sourceData[index];
// Package Name
var label0 = element.Q<Label>("Label0");
label0.text = providerInfo.PackageName;
// Asset Path // Asset Path
var label1 = element.Q<Label>("Label1"); var label1 = element.Q<Label>("Label1");
label1.text = providerInfo.AssetPath; label1.text = providerInfo.AssetPath;
@@ -177,19 +210,23 @@ namespace YooAsset.Editor
var label3 = element.Q<Label>("Label3"); var label3 = element.Q<Label>("Label3");
label3.text = providerInfo.SpawnTime; label3.text = providerInfo.SpawnTime;
// Ref Count // Loading Time
var label4 = element.Q<Label>("Label4"); var label4 = element.Q<Label>("Label4");
label4.text = providerInfo.RefCount.ToString(); label4.text = providerInfo.LoadingTime.ToString();
// Ref Count
var label5 = element.Q<Label>("Label5");
label5.text = providerInfo.RefCount.ToString();
// Status // Status
StyleColor textColor; StyleColor textColor;
if (providerInfo.Status == (int)ProviderBase.EStatus.Fail) if (providerInfo.Status == ProviderBase.EStatus.Failed.ToString())
textColor = new StyleColor(Color.yellow); textColor = new StyleColor(Color.yellow);
else else
textColor = label1.style.color; textColor = label1.style.color;
var label5 = element.Q<Label>("Label5"); var label6 = element.Q<Label>("Label6");
label5.text = providerInfo.Status.ToString(); label6.text = providerInfo.Status.ToString();
label5.style.color = textColor; label6.style.color = textColor;
} }
private void AssetListView_onSelectionChange(IEnumerable<object> objs) private void AssetListView_onSelectionChange(IEnumerable<object> objs)
{ {
@@ -200,7 +237,7 @@ namespace YooAsset.Editor
} }
} }
// 依赖列表相关 // 底部列表相关
private VisualElement MakeDependListViewItem() private VisualElement MakeDependListViewItem()
{ {
VisualElement element = new VisualElement(); VisualElement element = new VisualElement();
@@ -255,11 +292,11 @@ namespace YooAsset.Editor
var label4 = element.Q<Label>("Label4"); var label4 = element.Q<Label>("Label4");
label4.text = bundleInfo.Status.ToString(); label4.text = bundleInfo.Status.ToString();
} }
private void FillDependListView(DebugProviderInfo providerInfo) private void FillDependListView(DebugProviderInfo selectedProviderInfo)
{ {
_dependListView.Clear(); _dependListView.Clear();
_dependListView.ClearSelection(); _dependListView.ClearSelection();
_dependListView.itemsSource = providerInfo.DependBundleInfos; _dependListView.itemsSource = selectedProviderInfo.DependBundleInfos;
_dependListView.Rebuild(); _dependListView.Rebuild();
} }
} }

View File

@@ -1,11 +1,13 @@
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False"> <ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False">
<ui:VisualElement name="TopGroup" style="flex-grow: 1; border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-left-color: rgb(0, 0, 0); border-right-color: rgb(0, 0, 0); border-top-color: rgb(0, 0, 0); border-bottom-color: rgb(0, 0, 0); margin-left: 0; margin-right: 0; margin-top: 2px; margin-bottom: 1px; display: flex;"> <ui:VisualElement name="TopGroup" style="flex-grow: 1; border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-left-color: rgb(0, 0, 0); border-right-color: rgb(0, 0, 0); border-top-color: rgb(0, 0, 0); border-bottom-color: rgb(0, 0, 0); margin-left: 0; margin-right: 0; margin-top: 2px; margin-bottom: 1px; display: flex;">
<uie:Toolbar name="TopBar" style="height: 25px; margin-left: 1px; margin-right: 1px;"> <uie:Toolbar name="TopBar" style="height: 25px; margin-left: 1px; margin-right: 1px;">
<uie:ToolbarButton text="Package Name" display-tooltip-when-elided="true" name="TopBar0" style="width: 150px; -unity-text-align: middle-left; flex-grow: 0;" />
<uie:ToolbarButton text="Asset Path" display-tooltip-when-elided="true" name="TopBar1" style="width: 280px; -unity-text-align: middle-left; flex-grow: 1;" /> <uie:ToolbarButton text="Asset Path" display-tooltip-when-elided="true" name="TopBar1" style="width: 280px; -unity-text-align: middle-left; flex-grow: 1;" />
<uie:ToolbarButton text="Spawn Scene" display-tooltip-when-elided="true" name="TopBar2" style="width: 150px; -unity-text-align: middle-left; flex-grow: 0;" /> <uie:ToolbarButton text="Spawn Scene" display-tooltip-when-elided="true" name="TopBar2" style="width: 150px; -unity-text-align: middle-left; flex-grow: 0;" />
<uie:ToolbarButton text="Spawn Time" display-tooltip-when-elided="true" name="TopBar3" style="width: 150px; -unity-text-align: middle-left; flex-grow: 0;" /> <uie:ToolbarButton text="Spawn Time" display-tooltip-when-elided="true" name="TopBar3" style="width: 150px; -unity-text-align: middle-left; flex-grow: 0;" />
<uie:ToolbarButton text="Ref Count" display-tooltip-when-elided="true" name="TopBar4" style="width: 100px; -unity-text-align: middle-left; flex-grow: 0;" /> <uie:ToolbarButton text="Loading Time (ms)" display-tooltip-when-elided="true" name="TopBar4" style="width: 150px; -unity-text-align: middle-left; flex-grow: 0;" />
<uie:ToolbarButton text="Status" display-tooltip-when-elided="true" name="TopBar5" style="width: 120px; -unity-text-align: middle-left;" /> <uie:ToolbarButton text="Ref Count" display-tooltip-when-elided="true" name="TopBar5" style="width: 100px; -unity-text-align: middle-left; flex-grow: 0;" />
<uie:ToolbarButton text="Status" display-tooltip-when-elided="true" name="TopBar6" style="width: 120px; -unity-text-align: middle-left;" />
</uie:Toolbar> </uie:Toolbar>
<ui:ListView focusable="true" name="TopListView" item-height="18" virtualization-method="DynamicHeight" style="flex-grow: 1;" /> <ui:ListView focusable="true" name="TopListView" item-height="18" virtualization-method="DynamicHeight" style="flex-grow: 1;" />
</ui:VisualElement> </ui:VisualElement>

View File

@@ -27,14 +27,14 @@ namespace YooAsset.Editor
_visualAsset = EditorHelper.LoadWindowUXML<DebuggerBundleListViewer>(); _visualAsset = EditorHelper.LoadWindowUXML<DebuggerBundleListViewer>();
if (_visualAsset == null) if (_visualAsset == null)
return; return;
_root = _visualAsset.CloneTree(); _root = _visualAsset.CloneTree();
_root.style.flexGrow = 1f; _root.style.flexGrow = 1f;
// 资源包列表 // 资源包列表
_bundleListView = _root.Q<ListView>("TopListView"); _bundleListView = _root.Q<ListView>("TopListView");
_bundleListView.makeItem = MakeAssetListViewItem; _bundleListView.makeItem = MakeBundleListViewItem;
_bundleListView.bindItem = BindAssetListViewItem; _bundleListView.bindItem = BindBundleListViewItem;
#if UNITY_2020_1_OR_NEWER #if UNITY_2020_1_OR_NEWER
_bundleListView.onSelectionChange += BundleListView_onSelectionChange; _bundleListView.onSelectionChange += BundleListView_onSelectionChange;
#else #else
@@ -46,7 +46,7 @@ namespace YooAsset.Editor
_usingListView.makeItem = MakeIncludeListViewItem; _usingListView.makeItem = MakeIncludeListViewItem;
_usingListView.bindItem = BindIncludeListViewItem; _usingListView.bindItem = BindIncludeListViewItem;
} }
/// <summary> /// <summary>
/// 清空页面 /// 清空页面
/// </summary> /// </summary>
@@ -72,21 +72,33 @@ namespace YooAsset.Editor
} }
private List<DebugBundleInfo> FilterViewItems(DebugReport debugReport, string searchKeyWord) private List<DebugBundleInfo> FilterViewItems(DebugReport debugReport, string searchKeyWord)
{ {
Dictionary<string, DebugBundleInfo> result = new Dictionary<string, DebugBundleInfo>(debugReport.ProviderInfos.Count); List<DebugBundleInfo> result = new List<DebugBundleInfo>(1000);
foreach (var providerInfo in debugReport.ProviderInfos) foreach (var pakcageData in debugReport.PackageDatas)
{ {
foreach (var bundleInfo in providerInfo.DependBundleInfos) Dictionary<string, DebugBundleInfo> tempDic = new Dictionary<string, DebugBundleInfo>(1000);
foreach (var providerInfo in pakcageData.ProviderInfos)
{ {
if (string.IsNullOrEmpty(searchKeyWord) == false) foreach (var bundleInfo in providerInfo.DependBundleInfos)
{ {
if (bundleInfo.BundleName.Contains(searchKeyWord) == false) if (string.IsNullOrEmpty(searchKeyWord) == false)
continue; {
if (bundleInfo.BundleName.Contains(searchKeyWord) == false)
continue;
}
if (tempDic.ContainsKey(bundleInfo.BundleName) == false)
{
bundleInfo.PackageName = pakcageData.PackageName;
tempDic.Add(bundleInfo.BundleName, bundleInfo);
}
} }
if (result.ContainsKey(bundleInfo.BundleName) == false)
result.Add(bundleInfo.BundleName, bundleInfo);
} }
var tempList = tempDic.Values.ToList();
tempList.Sort();
result.AddRange(tempList);
} }
return result.Values.ToList(); return result;
} }
/// <summary> /// <summary>
@@ -107,11 +119,21 @@ namespace YooAsset.Editor
// 顶部列表相关 // 顶部列表相关
private VisualElement MakeAssetListViewItem() private VisualElement MakeBundleListViewItem()
{ {
VisualElement element = new VisualElement(); VisualElement element = new VisualElement();
element.style.flexDirection = FlexDirection.Row; element.style.flexDirection = FlexDirection.Row;
{
var label = new Label();
label.name = "Label0";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
//label.style.flexGrow = 1f;
label.style.width = 150;
element.Add(label);
}
{ {
var label = new Label(); var label = new Label();
label.name = "Label1"; label.name = "Label1";
@@ -144,11 +166,15 @@ namespace YooAsset.Editor
return element; return element;
} }
private void BindAssetListViewItem(VisualElement element, int index) private void BindBundleListViewItem(VisualElement element, int index)
{ {
var sourceData = _bundleListView.itemsSource as List<DebugBundleInfo>; var sourceData = _bundleListView.itemsSource as List<DebugBundleInfo>;
var bundleInfo = sourceData[index]; var bundleInfo = sourceData[index];
// Package Name
var label0 = element.Q<Label>("Label0");
label0.text = bundleInfo.PackageName;
// Bundle Name // Bundle Name
var label1 = element.Q<Label>("Label1"); var label1 = element.Q<Label>("Label1");
label1.text = bundleInfo.BundleName; label1.text = bundleInfo.BundleName;
@@ -159,7 +185,7 @@ namespace YooAsset.Editor
// Status // Status
StyleColor textColor; StyleColor textColor;
if (bundleInfo.Status == (int)AssetBundleLoaderBase.EStatus.Failed) if (bundleInfo.Status == BundleLoaderBase.EStatus.Failed.ToString())
textColor = new StyleColor(Color.yellow); textColor = new StyleColor(Color.yellow);
else else
textColor = label1.style.color; textColor = label1.style.color;
@@ -172,7 +198,7 @@ namespace YooAsset.Editor
foreach (var item in objs) foreach (var item in objs)
{ {
DebugBundleInfo bundleInfo = item as DebugBundleInfo; DebugBundleInfo bundleInfo = item as DebugBundleInfo;
FillUsingListView(bundleInfo.BundleName); FillUsingListView(bundleInfo);
} }
} }
@@ -259,17 +285,23 @@ namespace YooAsset.Editor
var label5 = element.Q<Label>("Label5"); var label5 = element.Q<Label>("Label5");
label5.text = providerInfo.Status.ToString(); label5.text = providerInfo.Status.ToString();
} }
private void FillUsingListView(string bundleName) private void FillUsingListView(DebugBundleInfo selectedBundleInfo)
{ {
List<DebugProviderInfo> source = new List<DebugProviderInfo>(); List<DebugProviderInfo> source = new List<DebugProviderInfo>();
foreach (var providerInfo in _debugReport.ProviderInfos) foreach (var packageData in _debugReport.PackageDatas)
{ {
foreach (var bundleInfo in providerInfo.DependBundleInfos) if (packageData.PackageName == selectedBundleInfo.PackageName)
{ {
if (bundleInfo.BundleName == bundleName) foreach (var providerInfo in packageData.ProviderInfos)
{ {
source.Add(providerInfo); foreach (var bundleInfo in providerInfo.DependBundleInfos)
continue; {
if (bundleInfo.BundleName == selectedBundleInfo.BundleName)
{
source.Add(providerInfo);
continue;
}
}
} }
} }
} }

View File

@@ -1,6 +1,7 @@
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False"> <ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False">
<ui:VisualElement name="TopGroup" style="flex-grow: 1; border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-left-color: rgb(0, 0, 0); border-right-color: rgb(0, 0, 0); border-top-color: rgb(0, 0, 0); border-bottom-color: rgb(0, 0, 0); margin-left: 0; margin-right: 0; margin-top: 2px; margin-bottom: 1px; display: flex;"> <ui:VisualElement name="TopGroup" style="flex-grow: 1; border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-left-color: rgb(0, 0, 0); border-right-color: rgb(0, 0, 0); border-top-color: rgb(0, 0, 0); border-bottom-color: rgb(0, 0, 0); margin-left: 0; margin-right: 0; margin-top: 2px; margin-bottom: 1px; display: flex;">
<uie:Toolbar name="TopBar" style="height: 25px; margin-left: 1px; margin-right: 1px;"> <uie:Toolbar name="TopBar" style="height: 25px; margin-left: 1px; margin-right: 1px;">
<uie:ToolbarButton text="Package Name" display-tooltip-when-elided="true" name="TopBar0" style="width: 150px; -unity-text-align: middle-left; flex-grow: 0;" />
<uie:ToolbarButton text="Bundle Name" display-tooltip-when-elided="true" name="TopBar1" style="width: 280px; -unity-text-align: middle-left; flex-grow: 1;" /> <uie:ToolbarButton text="Bundle Name" display-tooltip-when-elided="true" name="TopBar1" style="width: 280px; -unity-text-align: middle-left; flex-grow: 1;" />
<uie:ToolbarButton text="Ref Count" display-tooltip-when-elided="true" name="TopBar3" style="width: 100px; -unity-text-align: middle-left;" /> <uie:ToolbarButton text="Ref Count" display-tooltip-when-elided="true" name="TopBar3" style="width: 100px; -unity-text-align: middle-left;" />
<uie:ToolbarButton text="Status" display-tooltip-when-elided="true" name="TopBar4" style="width: 120px; -unity-text-align: middle-left;" /> <uie:ToolbarButton text="Status" display-tooltip-when-elided="true" name="TopBar4" style="width: 120px; -unity-text-align: middle-left;" />

View File

@@ -109,7 +109,7 @@ namespace YooAsset.Editor
return; return;
_reportFilePath = selectFilePath; _reportFilePath = selectFilePath;
string jsonData = FileUtility.ReadFile(_reportFilePath); string jsonData = FileUtility.ReadAllText(_reportFilePath);
_buildReport = BuildReport.Deserialize(jsonData); _buildReport = BuildReport.Deserialize(jsonData);
_assetListViewer.FillViewData(_buildReport, _searchKeyWord); _assetListViewer.FillViewData(_buildReport, _searchKeyWord);
_bundleListViewer.FillViewData(_buildReport, _reportFilePath, _searchKeyWord); _bundleListViewer.FillViewData(_buildReport, _reportFilePath, _searchKeyWord);

View File

@@ -25,7 +25,7 @@ namespace YooAsset.Editor
private ToolbarButton _topBar1; private ToolbarButton _topBar1;
private ToolbarButton _topBar2; private ToolbarButton _topBar2;
private ToolbarButton _topBar3; private ToolbarButton _topBar3;
private ToolbarButton _topBar4; private ToolbarButton _topBar5;
private ToolbarButton _bottomBar1; private ToolbarButton _bottomBar1;
private ListView _bundleListView; private ListView _bundleListView;
private ListView _includeListView; private ListView _includeListView;
@@ -53,11 +53,11 @@ namespace YooAsset.Editor
_topBar1 = _root.Q<ToolbarButton>("TopBar1"); _topBar1 = _root.Q<ToolbarButton>("TopBar1");
_topBar2 = _root.Q<ToolbarButton>("TopBar2"); _topBar2 = _root.Q<ToolbarButton>("TopBar2");
_topBar3 = _root.Q<ToolbarButton>("TopBar3"); _topBar3 = _root.Q<ToolbarButton>("TopBar3");
_topBar4 = _root.Q<ToolbarButton>("TopBar4"); _topBar5 = _root.Q<ToolbarButton>("TopBar5");
_topBar1.clicked += TopBar1_clicked; _topBar1.clicked += TopBar1_clicked;
_topBar2.clicked += TopBar2_clicked; _topBar2.clicked += TopBar2_clicked;
_topBar3.clicked += TopBar3_clicked; _topBar3.clicked += TopBar3_clicked;
_topBar4.clicked += TopBar4_clicked; _topBar5.clicked += TopBar4_clicked;
// 底部按钮栏 // 底部按钮栏
_bottomBar1 = _root.Q<ToolbarButton>("BottomBar1"); _bottomBar1 = _root.Q<ToolbarButton>("BottomBar1");
@@ -144,7 +144,7 @@ namespace YooAsset.Editor
_topBar1.text = $"Bundle Name ({_bundleListView.itemsSource.Count})"; _topBar1.text = $"Bundle Name ({_bundleListView.itemsSource.Count})";
_topBar2.text = "Size"; _topBar2.text = "Size";
_topBar3.text = "Hash"; _topBar3.text = "Hash";
_topBar4.text = "Tags"; _topBar5.text = "Tags";
if (_sortMode == ESortMode.BundleName) if (_sortMode == ESortMode.BundleName)
{ {
@@ -163,9 +163,9 @@ namespace YooAsset.Editor
else if (_sortMode == ESortMode.BundleTags) else if (_sortMode == ESortMode.BundleTags)
{ {
if (_descendingSort) if (_descendingSort)
_topBar4.text = "Tags ↓"; _topBar5.text = "Tags ↓";
else else
_topBar4.text = "Tags ↑"; _topBar5.text = "Tags ↑";
} }
else else
{ {
@@ -231,6 +231,16 @@ namespace YooAsset.Editor
label.name = "Label5"; label.name = "Label5";
label.style.unityTextAlign = TextAnchor.MiddleLeft; label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f; label.style.marginLeft = 3f;
//label.style.flexGrow = 1f;
label.style.width = 150;
element.Add(label);
}
{
var label = new Label();
label.name = "Label6";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
label.style.flexGrow = 1f; label.style.flexGrow = 1f;
label.style.width = 80; label.style.width = 80;
element.Add(label); element.Add(label);
@@ -255,9 +265,13 @@ namespace YooAsset.Editor
var label3 = element.Q<Label>("Label3"); var label3 = element.Q<Label>("Label3");
label3.text = bundleInfo.FileHash; label3.text = bundleInfo.FileHash;
// Tags // LoadMethod
var label5 = element.Q<Label>("Label5"); var label5 = element.Q<Label>("Label5");
label5.text = bundleInfo.GetTagsString(); label5.text = bundleInfo.LoadMethod.ToString();
// Tags
var label6 = element.Q<Label>("Label6");
label6.text = bundleInfo.GetTagsString();
} }
private void BundleListView_onSelectionChange(IEnumerable<object> objs) private void BundleListView_onSelectionChange(IEnumerable<object> objs)
{ {
@@ -271,7 +285,7 @@ namespace YooAsset.Editor
} }
private void ShowAssetBundleInspector(ReportBundleInfo bundleInfo) private void ShowAssetBundleInspector(ReportBundleInfo bundleInfo)
{ {
if (bundleInfo.IsRawFile()) if (bundleInfo.IsRawFile)
return; return;
string rootDirectory = Path.GetDirectoryName(_reportFilePath); string rootDirectory = Path.GetDirectoryName(_reportFilePath);

View File

@@ -5,7 +5,8 @@
<uie:ToolbarButton text="Bundle Name" display-tooltip-when-elided="true" name="TopBar1" style="width: 280px; -unity-text-align: middle-left; flex-grow: 1;" /> <uie:ToolbarButton text="Bundle Name" display-tooltip-when-elided="true" name="TopBar1" style="width: 280px; -unity-text-align: middle-left; flex-grow: 1;" />
<uie:ToolbarButton text="Size" display-tooltip-when-elided="true" name="TopBar2" style="width: 100px; -unity-text-align: middle-left; flex-grow: 0;" /> <uie:ToolbarButton text="Size" display-tooltip-when-elided="true" name="TopBar2" style="width: 100px; -unity-text-align: middle-left; flex-grow: 0;" />
<uie:ToolbarButton text="Hash" display-tooltip-when-elided="true" name="TopBar3" style="width: 280px; -unity-text-align: middle-left;" /> <uie:ToolbarButton text="Hash" display-tooltip-when-elided="true" name="TopBar3" style="width: 280px; -unity-text-align: middle-left;" />
<uie:ToolbarButton text="Tags" display-tooltip-when-elided="true" name="TopBar4" style="width: 80px; -unity-text-align: middle-left; flex-grow: 1;" /> <uie:ToolbarButton text="LoadMethod" display-tooltip-when-elided="true" name="TopBar4" style="width: 150px; -unity-text-align: middle-left; flex-grow: 0;" />
<uie:ToolbarButton text="Tags" display-tooltip-when-elided="true" name="TopBar5" style="width: 80px; -unity-text-align: middle-left; flex-grow: 1;" />
</uie:Toolbar> </uie:Toolbar>
<ui:ListView focusable="true" name="TopListView" item-height="18" virtualization-method="DynamicHeight" style="flex-grow: 1;" /> <ui:ListView focusable="true" name="TopListView" item-height="18" virtualization-method="DynamicHeight" style="flex-grow: 1;" />
</ui:VisualElement> </ui:VisualElement>

View File

@@ -66,7 +66,8 @@ namespace YooAsset.Editor
_items.Add(new ItemWrapper("构建平台", $"{buildReport.Summary.BuildTarget}")); _items.Add(new ItemWrapper("构建平台", $"{buildReport.Summary.BuildTarget}"));
_items.Add(new ItemWrapper("构建管线", $"{buildReport.Summary.BuildPipeline}")); _items.Add(new ItemWrapper("构建管线", $"{buildReport.Summary.BuildPipeline}"));
_items.Add(new ItemWrapper("构建模式", $"{buildReport.Summary.BuildMode}")); _items.Add(new ItemWrapper("构建模式", $"{buildReport.Summary.BuildMode}"));
_items.Add(new ItemWrapper("构建包裹", $"{buildReport.Summary.BuildPackage}")); _items.Add(new ItemWrapper("包裹名称", buildReport.Summary.BuildPackageName));
_items.Add(new ItemWrapper("包裹版本", buildReport.Summary.BuildPackageVersion));
_items.Add(new ItemWrapper("启用可寻址资源定位", $"{buildReport.Summary.EnableAddressable}")); _items.Add(new ItemWrapper("启用可寻址资源定位", $"{buildReport.Summary.EnableAddressable}"));
_items.Add(new ItemWrapper("资源包名唯一化", $"{buildReport.Summary.UniqueBundleName}")); _items.Add(new ItemWrapper("资源包名唯一化", $"{buildReport.Summary.UniqueBundleName}"));

View File

@@ -0,0 +1,36 @@
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 EditorAttribute
{
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,5 +1,5 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: 60c7594328ef976408edadfdf2b9aa3d guid: 92d5f73b21059af43b7f56165b7acd63
MonoImporter: MonoImporter:
externalObjects: {} externalObjects: {}
serializedVersion: 2 serializedVersion: 2

View File

@@ -8,7 +8,14 @@ namespace YooAsset.Editor
/// <summary> /// <summary>
/// 停靠窗口类型集合 /// 停靠窗口类型集合
/// </summary> /// </summary>
public static readonly Type[] DockedWindowTypes = { typeof(AssetBundleBuilderWindow), typeof(AssetBundleCollectorWindow), typeof(AssetBundleDebuggerWindow), typeof(AssetBundleReporterWindow)}; public static readonly Type[] DockedWindowTypes =
{
typeof(AssetBundleBuilderWindow),
typeof(AssetBundleCollectorWindow),
typeof(AssetBundleDebuggerWindow),
typeof(AssetBundleReporterWindow),
typeof(ShaderVariantCollectorWindow)
};
#endif #endif
} }

View File

@@ -10,6 +10,7 @@ namespace YooAsset.Editor
#if UNITY_2019_4_OR_NEWER #if UNITY_2019_4_OR_NEWER
private readonly static Dictionary<System.Type, string> _uxmlDic = new Dictionary<System.Type, string>(); private readonly static Dictionary<System.Type, string> _uxmlDic = new Dictionary<System.Type, string>();
/*
static EditorHelper() static EditorHelper()
{ {
// 资源包收集 // 资源包收集
@@ -51,6 +52,46 @@ namespace YooAsset.Editor
throw new System.Exception($"Invalid YooAsset window type : {windowType}"); throw new System.Exception($"Invalid YooAsset window type : {windowType}");
} }
} }
*/
/// <summary>
/// 加载窗口的布局文件
/// </summary>
public static UnityEngine.UIElements.VisualTreeAsset LoadWindowUXML<TWindow>() where TWindow : class
{
var windowType = typeof(TWindow);
// 缓存里查询并加载
if (_uxmlDic.TryGetValue(windowType, out string uxmlGUID))
{
string assetPath = AssetDatabase.GUIDToAssetPath(uxmlGUID);
if (string.IsNullOrEmpty(assetPath))
{
_uxmlDic.Clear();
throw new System.Exception($"Invalid UXML GUID : {uxmlGUID} ! Please close the window and open it again !");
}
var treeAsset = AssetDatabase.LoadAssetAtPath<UnityEngine.UIElements.VisualTreeAsset>(assetPath);
return treeAsset;
}
// 全局搜索并加载
string[] guids = AssetDatabase.FindAssets(windowType.Name);
if (guids.Length == 0)
throw new System.Exception($"Not found any assets : {windowType.Name}");
foreach (string assetGUID in guids)
{
string assetPath = AssetDatabase.GUIDToAssetPath(assetGUID);
var assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
if (assetType == typeof(UnityEngine.UIElements.VisualTreeAsset))
{
_uxmlDic.Add(windowType, assetGUID);
var treeAsset = AssetDatabase.LoadAssetAtPath<UnityEngine.UIElements.VisualTreeAsset>(assetPath);
return treeAsset;
}
}
throw new System.Exception($"Not found UXML file : {windowType.Name}");
}
#endif #endif
/// <summary> /// <summary>

View File

@@ -285,6 +285,35 @@ namespace YooAsset.Editor
} }
#endregion #endregion
#region StringUtility
public static List<string> StringToStringList(string str, char separator)
{
List<string> result = new List<string>();
if (!String.IsNullOrEmpty(str))
{
string[] splits = str.Split(separator);
foreach (string split in splits)
{
string value = split.Trim(); //移除首尾空格
if (!String.IsNullOrEmpty(value))
{
result.Add(value);
}
}
}
return result;
}
public static T NameToEnum<T>(string name)
{
if (Enum.IsDefined(typeof(T), name) == false)
{
throw new ArgumentException($"Enum {typeof(T)} is not defined name {name}");
}
return (T)Enum.Parse(typeof(T), name);
}
#endregion
#region #region
/// <summary> /// <summary>
/// 创建文件所在的目录 /// 创建文件所在的目录
@@ -349,9 +378,9 @@ namespace YooAsset.Editor
} }
/// <summary> /// <summary>
/// 文件移动 /// 移动文件
/// </summary> /// </summary>
public static void FileMoveTo(string filePath, string destPath) public static void MoveFile(string filePath, string destPath)
{ {
if (File.Exists(destPath)) if (File.Exists(destPath))
File.Delete(destPath); File.Delete(destPath);
@@ -359,7 +388,7 @@ namespace YooAsset.Editor
FileInfo fileInfo = new FileInfo(filePath); FileInfo fileInfo = new FileInfo(filePath);
fileInfo.MoveTo(destPath); fileInfo.MoveTo(destPath);
} }
/// <summary> /// <summary>
/// 拷贝文件夹 /// 拷贝文件夹
/// 注意:包括所有子目录的文件 /// 注意:包括所有子目录的文件

View File

@@ -9,7 +9,8 @@ using UnityEditor;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
public static class ShaderVariantCollectionReadme [Serializable]
public class ShaderVariantCollectionManifest
{ {
[Serializable] [Serializable]
public class ShaderVariantElement public class ShaderVariantElement
@@ -44,52 +45,49 @@ namespace YooAsset.Editor
public List<ShaderVariantElement> ShaderVariantElements = new List<ShaderVariantElement>(1000); public List<ShaderVariantElement> ShaderVariantElements = new List<ShaderVariantElement>(1000);
} }
[Serializable]
public class ShaderVariantCollectionManifest /// <summary>
/// Number of shaders in this collection
/// </summary>
public int ShaderTotalCount;
/// <summary>
/// Number of total varians in this collection
/// </summary>
public int VariantTotalCount;
/// <summary>
/// Shader variants info list.
/// </summary>
public List<ShaderVariantInfo> ShaderVariantInfos = new List<ShaderVariantInfo>(1000);
/// <summary>
/// 添加着色器变种信息
/// </summary>
public void AddShaderVariant(string assetPath, string shaderName, PassType passType, string[] keywords)
{ {
/// <summary> var info = GetOrCreateShaderVariantInfo(assetPath, shaderName);
/// Number of shaders in this collection ShaderVariantElement element = new ShaderVariantElement();
/// </summary> element.PassType = passType;
public int ShaderTotalCount; element.Keywords = keywords;
info.ShaderVariantElements.Add(element);
/// <summary> }
/// Number of total varians in this collection private ShaderVariantInfo GetOrCreateShaderVariantInfo(string assetPath, string shaderName)
/// </summary> {
public int VariantTotalCount; var selectList = ShaderVariantInfos.Where(t => t.ShaderName == shaderName && t.AssetPath == assetPath).ToList();
if (selectList.Count == 0)
/// <summary>
/// Shader variants info list.
/// </summary>
public List<ShaderVariantInfo> ShaderVariantInfos = new List<ShaderVariantInfo>(1000);
/// <summary>
/// 添加着色器变种信息
/// </summary>
public void AddShaderVariant(string assetPath, string shaderName, PassType passType, string[] keywords)
{ {
var info = GetOrCreateShaderVariantInfo(assetPath, shaderName); ShaderVariantInfo newInfo = new ShaderVariantInfo();
ShaderVariantElement element = new ShaderVariantElement(); newInfo.AssetPath = assetPath;
element.PassType = passType; newInfo.ShaderName = shaderName;
element.Keywords = keywords; ShaderVariantInfos.Add(newInfo);
info.ShaderVariantElements.Add(element); return newInfo;
} }
private ShaderVariantInfo GetOrCreateShaderVariantInfo(string assetPath, string shaderName)
{
var selectList = ShaderVariantInfos.Where(t => t.ShaderName == shaderName && t.AssetPath == assetPath).ToList();
if (selectList.Count == 0)
{
ShaderVariantInfo newInfo = new ShaderVariantInfo();
newInfo.AssetPath = assetPath;
newInfo.ShaderName = shaderName;
ShaderVariantInfos.Add(newInfo);
return newInfo;
}
if (selectList.Count != 1) if (selectList.Count != 1)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
return selectList[0]; return selectList[0];
}
} }

View File

@@ -30,8 +30,8 @@ namespace YooAsset.Editor
// 保存结果 // 保存结果
ShaderVariantCollectionHelper.SaveCurrentShaderVariantCollection(_saveFilePath); ShaderVariantCollectionHelper.SaveCurrentShaderVariantCollection(_saveFilePath);
// 创建说明文件 // 创建清单
CreateReadme(); CreateManifest();
Debug.Log($"搜集SVC完毕"); Debug.Log($"搜集SVC完毕");
_completedCallback?.Invoke(); _completedCallback?.Invoke();
@@ -64,7 +64,7 @@ namespace YooAsset.Editor
ShaderVariantCollectionHelper.ClearCurrentShaderVariantCollection(); ShaderVariantCollectionHelper.ClearCurrentShaderVariantCollection();
// 创建临时测试场景 // 创建临时测试场景
CreateTemperScene(); CreateTempScene();
// 收集着色器变种 // 收集着色器变种
var materials = GetAllMaterials(); var materials = GetAllMaterials();
@@ -76,9 +76,8 @@ namespace YooAsset.Editor
_elapsedTime.Start(); _elapsedTime.Start();
} }
private static void CreateTemperScene() private static void CreateTempScene()
{ {
// 创建临时场景
EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects); EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects);
} }
private static List<Material> GetAllMaterials() private static List<Material> GetAllMaterials()
@@ -186,17 +185,17 @@ namespace YooAsset.Editor
go.transform.position = position; go.transform.position = position;
go.name = $"Sphere_{index}|{material.name}"; go.name = $"Sphere_{index}|{material.name}";
} }
private static void CreateReadme() private static void CreateManifest()
{ {
AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
ShaderVariantCollection svc = AssetDatabase.LoadAssetAtPath<ShaderVariantCollection>(_saveFilePath); ShaderVariantCollection svc = AssetDatabase.LoadAssetAtPath<ShaderVariantCollection>(_saveFilePath);
if (svc != null) if (svc != null)
{ {
var wrapper = ShaderVariantCollectionReadme.Extract(svc); var wrapper = ShaderVariantCollectionManifest.Extract(svc);
string jsonContents = JsonUtility.ToJson(wrapper, true); string jsonData = JsonUtility.ToJson(wrapper, true);
string savePath = _saveFilePath.Replace(".shadervariants", "Manifest.json"); string savePath = _saveFilePath.Replace(".shadervariants", ".json");
File.WriteAllText(savePath, jsonContents); File.WriteAllText(savePath, jsonData);
} }
AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);

View File

@@ -1,61 +1,82 @@
using UnityEngine; #if UNITY_2019_4_OR_NEWER
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEditor; using UnityEditor;
using UnityEngine;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
public class ShaderVariantCollectionWindow : EditorWindow public class ShaderVariantCollectorWindow : EditorWindow
{ {
static ShaderVariantCollectionWindow _thisInstance;
[MenuItem("YooAsset/ShaderVariant Collector", false, 201)] [MenuItem("YooAsset/ShaderVariant Collector", false, 201)]
static void ShowWindow() public static void ShowExample()
{ {
if (_thisInstance == null) ShaderVariantCollectorWindow window = GetWindow<ShaderVariantCollectorWindow>("着色器变种收集工具", true, EditorDefine.DockedWindowTypes);
{ window.minSize = new Vector2(800, 600);
_thisInstance = GetWindow<ShaderVariantCollectionWindow>("着色器变种收集工具");
_thisInstance.minSize = new Vector2(800, 600);
}
_thisInstance.Show();
} }
private ShaderVariantCollection _selectSVC; private Button _collectButton;
private TextField _collectOutputField;
private Label _currentShaderCountField;
private Label _currentVariantCountField;
private void OnGUI() public void CreateGUI()
{ {
EditorGUILayout.Space(); try
ShaderVariantCollectorSettingData.Setting.SavePath = EditorGUILayout.TextField("收集文件保存路径", ShaderVariantCollectorSettingData.Setting.SavePath);
int currentShaderCount = ShaderVariantCollectionHelper.GetCurrentShaderVariantCollectionShaderCount();
int currentVariantCount = ShaderVariantCollectionHelper.GetCurrentShaderVariantCollectionVariantCount();
EditorGUILayout.LabelField($"CurrentShaderCount : {currentShaderCount}");
EditorGUILayout.LabelField($"CurrentVariantCount : {currentVariantCount}");
// 搜集变种
EditorGUILayout.Space();
if (GUILayout.Button("搜集变种", GUILayout.MaxWidth(80)))
{ {
ShaderVariantCollector.Run(ShaderVariantCollectorSettingData.Setting.SavePath, null); VisualElement root = this.rootVisualElement;
}
// 查询 // 加载布局文件
EditorGUILayout.Space(); var visualAsset = EditorHelper.LoadWindowUXML<ShaderVariantCollectorWindow>();
if (GUILayout.Button("查询", GUILayout.MaxWidth(80))) if (visualAsset == null)
{
string resultPath = EditorTools.OpenFilePath("Select File", "Assets/", "shadervariants");
if (string.IsNullOrEmpty(resultPath))
return; return;
string assetPath = EditorTools.AbsolutePathToAssetPath(resultPath);
_selectSVC = AssetDatabase.LoadAssetAtPath<ShaderVariantCollection>(assetPath); visualAsset.CloneTree(root);
// 文件输出目录
_collectOutputField = root.Q<TextField>("CollectOutput");
_collectOutputField.SetValueWithoutNotify(ShaderVariantCollectorSettingData.Setting.SavePath);
_collectOutputField.RegisterValueChangedCallback(evt =>
{
ShaderVariantCollectorSettingData.Setting.SavePath = _collectOutputField.value;
});
_currentShaderCountField = root.Q<Label>("CurrentShaderCount");
_currentVariantCountField = root.Q<Label>("CurrentVariantCount");
// 变种收集按钮
_collectButton = root.Q<Button>("CollectButton");
_collectButton.clicked += CollectButton_clicked;
//RefreshWindow();
} }
if (_selectSVC != null) catch (Exception e)
{ {
EditorGUILayout.LabelField($"ShaderCount : {_selectSVC.shaderCount}"); Debug.LogError(e.ToString());
EditorGUILayout.LabelField($"VariantCount : {_selectSVC.variantCount}");
} }
} }
private void OnDestroy() private void Update()
{ {
ShaderVariantCollectorSettingData.SaveFile(); if (_currentShaderCountField != null)
{
int currentShaderCount = ShaderVariantCollectionHelper.GetCurrentShaderVariantCollectionShaderCount();
_currentShaderCountField.text = $"Current Shader Count : {currentShaderCount}";
}
if (_currentVariantCountField != null)
{
int currentVariantCount = ShaderVariantCollectionHelper.GetCurrentShaderVariantCollectionVariantCount();
_currentVariantCountField.text = $"Current Variant Count : {currentVariantCount}";
}
}
private void CollectButton_clicked()
{
ShaderVariantCollector.Run(ShaderVariantCollectorSettingData.Setting.SavePath, null);
} }
} }
} }
#endif

View File

@@ -0,0 +1,9 @@
<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;" />
<ui:VisualElement name="BuildContainer">
<ui:TextField picking-mode="Ignore" label="文件保存路径" name="CollectOutput" />
<ui:Label text="Current Shader Count" display-tooltip-when-elided="true" name="CurrentShaderCount" />
<ui:Label text="Current Variant Count" display-tooltip-when-elided="true" name="CurrentVariantCount" />
<ui:Button text="开始搜集" display-tooltip-when-elided="true" name="CollectButton" style="height: 50px; background-color: rgb(40, 106, 42); margin-top: 10px;" />
</ui:VisualElement>
</ui:UXML>

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 9bff4878063eaf04dab8713e1e662ac5
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 13804, guid: 0000000000000000e000000000000000, type: 0}

View File

@@ -8,13 +8,12 @@ namespace YooAsset
{ {
internal class AssetSystemImpl internal class AssetSystemImpl
{ {
private static string SceneRunningPackage = string.Empty; private readonly List<BundleLoaderBase> _loaders = new List<BundleLoaderBase>(1000);
private readonly List<AssetBundleLoaderBase> _loaders = new List<AssetBundleLoaderBase>(1000);
private readonly List<ProviderBase> _providers = new List<ProviderBase>(1000); private readonly List<ProviderBase> _providers = new List<ProviderBase>(1000);
private readonly Dictionary<string, SceneOperationHandle> _sceneHandles = new Dictionary<string, SceneOperationHandle>(100); private readonly static Dictionary<string, SceneOperationHandle> _sceneHandles = new Dictionary<string, SceneOperationHandle>(100);
private static long _sceneCreateCount = 0;
private long _sceneCreateCount = 0; private string _packageName;
private bool _simulationOnEditor; private bool _simulationOnEditor;
private int _loadingMaxNumber; private int _loadingMaxNumber;
public IDecryptionServices DecryptionServices { private set; get; } public IDecryptionServices DecryptionServices { private set; get; }
@@ -25,8 +24,9 @@ namespace YooAsset
/// 初始化 /// 初始化
/// 注意在使用AssetSystem之前需要初始化 /// 注意在使用AssetSystem之前需要初始化
/// </summary> /// </summary>
public void Initialize(bool simulationOnEditor, int loadingMaxNumber, IDecryptionServices decryptionServices, IBundleServices bundleServices) public void Initialize(string packageName, bool simulationOnEditor, int loadingMaxNumber, IDecryptionServices decryptionServices, IBundleServices bundleServices)
{ {
_packageName = packageName;
_simulationOnEditor = simulationOnEditor; _simulationOnEditor = simulationOnEditor;
_loadingMaxNumber = loadingMaxNumber; _loadingMaxNumber = loadingMaxNumber;
DecryptionServices = decryptionServices; DecryptionServices = decryptionServices;
@@ -71,10 +71,19 @@ namespace YooAsset
/// </summary> /// </summary>
public void DestroyAll() public void DestroyAll()
{ {
_loaders.Clear(); foreach (var provider in _providers)
{
provider.Destroy();
}
_providers.Clear(); _providers.Clear();
_sceneHandles.Clear();
foreach (var loader in _loaders)
{
loader.Destroy(true);
}
_loaders.Clear();
ClearSceneHandle();
DecryptionServices = null; DecryptionServices = null;
BundleServices = null; BundleServices = null;
} }
@@ -83,6 +92,15 @@ namespace YooAsset
/// 资源回收(卸载引用计数为零的资源) /// 资源回收(卸载引用计数为零的资源)
/// </summary> /// </summary>
public void UnloadUnusedAssets() public void UnloadUnusedAssets()
{
// 注意:资源包之间可能存在多层深层嵌套,需要多次循环释放。
int loopCount = 10;
for (int i = 0; i < loopCount; i++)
{
UnloadUnusedAssetsInternal();
}
}
private void UnloadUnusedAssetsInternal()
{ {
if (_simulationOnEditor) if (_simulationOnEditor)
{ {
@@ -99,12 +117,12 @@ namespace YooAsset
{ {
for (int i = _loaders.Count - 1; i >= 0; i--) for (int i = _loaders.Count - 1; i >= 0; i--)
{ {
AssetBundleLoaderBase loader = _loaders[i]; BundleLoaderBase loader = _loaders[i];
loader.TryDestroyAllProviders(); loader.TryDestroyAllProviders();
} }
for (int i = _loaders.Count - 1; i >= 0; i--) for (int i = _loaders.Count - 1; i >= 0; i--)
{ {
AssetBundleLoaderBase loader = _loaders[i]; BundleLoaderBase loader = _loaders[i];
if (loader.CanDestroy()) if (loader.CanDestroy())
{ {
loader.Destroy(false); loader.Destroy(false);
@@ -123,13 +141,14 @@ namespace YooAsset
{ {
provider.Destroy(); provider.Destroy();
} }
_providers.Clear();
foreach (var loader in _loaders) foreach (var loader in _loaders)
{ {
loader.Destroy(true); loader.Destroy(true);
} }
_providers.Clear();
_loaders.Clear(); _loaders.Clear();
ClearSceneHandle();
// 注意:调用底层接口释放所有资源 // 注意:调用底层接口释放所有资源
Resources.UnloadUnusedAssets(); Resources.UnloadUnusedAssets();
@@ -142,25 +161,12 @@ namespace YooAsset
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
{ {
YooLogger.Error($"Failed to load scene. {assetInfo.Error}"); YooLogger.Error($"Failed to load scene ! {assetInfo.Error}");
CompletedProvider completedProvider = new CompletedProvider(assetInfo); CompletedProvider completedProvider = new CompletedProvider(assetInfo);
completedProvider.SetCompleted(assetInfo.Error); completedProvider.SetCompleted(assetInfo.Error);
return completedProvider.CreateHandle<SceneOperationHandle>(); return completedProvider.CreateHandle<SceneOperationHandle>();
} }
// 注意:场景只允许运行在一个资源包内
if (string.IsNullOrEmpty(SceneRunningPackage))
{
SceneRunningPackage = BundleServices.GetPackageName();
}
if (BundleServices.GetPackageName() != SceneRunningPackage)
{
CompletedProvider completedProvider = new CompletedProvider(assetInfo);
string error = $"Scene are allowed to running within only {SceneRunningPackage}";
completedProvider.SetCompleted(error);
return completedProvider.CreateHandle<SceneOperationHandle>();
}
// 如果加载的是主场景,则卸载所有缓存的场景 // 如果加载的是主场景,则卸载所有缓存的场景
if (sceneMode == LoadSceneMode.Single) if (sceneMode == LoadSceneMode.Single)
{ {
@@ -180,6 +186,7 @@ namespace YooAsset
} }
var handle = provider.CreateHandle<SceneOperationHandle>(); var handle = provider.CreateHandle<SceneOperationHandle>();
handle.PackageName = _packageName;
_sceneHandles.Add(providerGUID, handle); _sceneHandles.Add(providerGUID, handle);
return handle; return handle;
} }
@@ -191,7 +198,7 @@ namespace YooAsset
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
{ {
YooLogger.Error($"Failed to load asset. {assetInfo.Error}"); YooLogger.Error($"Failed to load asset ! {assetInfo.Error}");
CompletedProvider completedProvider = new CompletedProvider(assetInfo); CompletedProvider completedProvider = new CompletedProvider(assetInfo);
completedProvider.SetCompleted(assetInfo.Error); completedProvider.SetCompleted(assetInfo.Error);
return completedProvider.CreateHandle<AssetOperationHandle>(); return completedProvider.CreateHandle<AssetOperationHandle>();
@@ -218,7 +225,7 @@ namespace YooAsset
{ {
if (assetInfo.IsInvalid) if (assetInfo.IsInvalid)
{ {
YooLogger.Error($"Failed to load sub assets. {assetInfo.Error}"); YooLogger.Error($"Failed to load sub assets ! {assetInfo.Error}");
CompletedProvider completedProvider = new CompletedProvider(assetInfo); CompletedProvider completedProvider = new CompletedProvider(assetInfo);
completedProvider.SetCompleted(assetInfo.Error); completedProvider.SetCompleted(assetInfo.Error);
return completedProvider.CreateHandle<SubAssetsOperationHandle>(); return completedProvider.CreateHandle<SubAssetsOperationHandle>();
@@ -238,6 +245,33 @@ namespace YooAsset
return provider.CreateHandle<SubAssetsOperationHandle>(); return provider.CreateHandle<SubAssetsOperationHandle>();
} }
/// <summary>
/// 加载原生文件
/// </summary>
public RawFileOperationHandle LoadRawFileAsync(AssetInfo assetInfo)
{
if (assetInfo.IsInvalid)
{
YooLogger.Error($"Failed to load raw file ! {assetInfo.Error}");
CompletedProvider completedProvider = new CompletedProvider(assetInfo);
completedProvider.SetCompleted(assetInfo.Error);
return completedProvider.CreateHandle<RawFileOperationHandle>();
}
string providerGUID = assetInfo.GUID;
ProviderBase provider = TryGetProvider(providerGUID);
if (provider == null)
{
if (_simulationOnEditor)
provider = new DatabaseRawFileProvider(this, providerGUID, assetInfo);
else
provider = new BundledRawFileProvider(this, providerGUID, assetInfo);
provider.InitSpawnDebugInfo();
_providers.Add(provider);
}
return provider.CreateHandle<RawFileOperationHandle>();
}
internal void UnloadSubScene(ProviderBase provider) internal void UnloadSubScene(ProviderBase provider)
{ {
string providerGUID = provider.ProviderGUID; string providerGUID = provider.ProviderGUID;
@@ -263,19 +297,39 @@ namespace YooAsset
// 卸载未被使用的资源(包括场景) // 卸载未被使用的资源(包括场景)
UnloadUnusedAssets(); UnloadUnusedAssets();
} }
internal void ClearSceneHandle()
{
// 释放资源包下的所有场景
if (BundleServices.IsServicesValid())
{
string packageName = _packageName;
List<string> removeList = new List<string>();
foreach (var valuePair in _sceneHandles)
{
if (valuePair.Value.PackageName == packageName)
{
removeList.Add(valuePair.Key);
}
}
foreach (var key in removeList)
{
_sceneHandles.Remove(key);
}
}
}
internal AssetBundleLoaderBase CreateOwnerAssetBundleLoader(AssetInfo assetInfo) internal BundleLoaderBase CreateOwnerAssetBundleLoader(AssetInfo assetInfo)
{ {
BundleInfo bundleInfo = BundleServices.GetBundleInfo(assetInfo); BundleInfo bundleInfo = BundleServices.GetBundleInfo(assetInfo);
return CreateAssetBundleLoaderInternal(bundleInfo); return CreateAssetBundleLoaderInternal(bundleInfo);
} }
internal List<AssetBundleLoaderBase> CreateDependAssetBundleLoaders(AssetInfo assetInfo) internal List<BundleLoaderBase> CreateDependAssetBundleLoaders(AssetInfo assetInfo)
{ {
BundleInfo[] depends = BundleServices.GetAllDependBundleInfos(assetInfo); BundleInfo[] depends = BundleServices.GetAllDependBundleInfos(assetInfo);
List<AssetBundleLoaderBase> result = new List<AssetBundleLoaderBase>(depends.Length); List<BundleLoaderBase> result = new List<BundleLoaderBase>(depends.Length);
foreach (var bundleInfo in depends) foreach (var bundleInfo in depends)
{ {
AssetBundleLoaderBase dependLoader = CreateAssetBundleLoaderInternal(bundleInfo); BundleLoaderBase dependLoader = CreateAssetBundleLoaderInternal(bundleInfo);
result.Add(dependLoader); result.Add(dependLoader);
} }
return result; return result;
@@ -288,10 +342,10 @@ namespace YooAsset
} }
} }
private AssetBundleLoaderBase CreateAssetBundleLoaderInternal(BundleInfo bundleInfo) private BundleLoaderBase CreateAssetBundleLoaderInternal(BundleInfo bundleInfo)
{ {
// 如果加载器已经存在 // 如果加载器已经存在
AssetBundleLoaderBase loader = TryGetAssetBundleLoader(bundleInfo.Bundle.BundleName); BundleLoaderBase loader = TryGetAssetBundleLoader(bundleInfo.Bundle.BundleName);
if (loader != null) if (loader != null)
return loader; return loader;
@@ -299,18 +353,21 @@ namespace YooAsset
#if UNITY_WEBGL #if UNITY_WEBGL
loader = new AssetBundleWebLoader(this, bundleInfo); loader = new AssetBundleWebLoader(this, bundleInfo);
#else #else
loader = new AssetBundleFileLoader(this, bundleInfo); if (bundleInfo.Bundle.IsRawFile)
loader = new RawBundleFileLoader(this, bundleInfo);
else
loader = new AssetBundleFileLoader(this, bundleInfo);
#endif #endif
_loaders.Add(loader); _loaders.Add(loader);
return loader; return loader;
} }
private AssetBundleLoaderBase TryGetAssetBundleLoader(string bundleName) private BundleLoaderBase TryGetAssetBundleLoader(string bundleName)
{ {
AssetBundleLoaderBase loader = null; BundleLoaderBase loader = null;
for (int i = 0; i < _loaders.Count; i++) for (int i = 0; i < _loaders.Count; i++)
{ {
AssetBundleLoaderBase temp = _loaders[i]; BundleLoaderBase temp = _loaders[i];
if (temp.MainBundleInfo.Bundle.BundleName.Equals(bundleName)) if (temp.MainBundleInfo.Bundle.BundleName.Equals(bundleName))
{ {
loader = temp; loader = temp;
@@ -341,12 +398,12 @@ namespace YooAsset
foreach (var provider in _providers) foreach (var provider in _providers)
{ {
DebugProviderInfo providerInfo = new DebugProviderInfo(); DebugProviderInfo providerInfo = new DebugProviderInfo();
providerInfo.PackageName = BundleServices.GetPackageName();
providerInfo.AssetPath = provider.MainAssetInfo.AssetPath; providerInfo.AssetPath = provider.MainAssetInfo.AssetPath;
providerInfo.SpawnScene = provider.SpawnScene; providerInfo.SpawnScene = provider.SpawnScene;
providerInfo.SpawnTime = provider.SpawnTime; providerInfo.SpawnTime = provider.SpawnTime;
providerInfo.LoadingTime = provider.LoadingTime;
providerInfo.RefCount = provider.RefCount; providerInfo.RefCount = provider.RefCount;
providerInfo.Status = (int)provider.Status; providerInfo.Status = provider.Status.ToString();
providerInfo.DependBundleInfos = new List<DebugBundleInfo>(); providerInfo.DependBundleInfos = new List<DebugBundleInfo>();
result.Add(providerInfo); result.Add(providerInfo);

View File

@@ -1,9 +1,10 @@
using UnityEngine; using System;
using System.Collections.Generic; using System.Collections.Generic;
using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
public sealed class AssetOperationHandle : OperationHandleBase public sealed class AssetOperationHandle : OperationHandleBase, IDisposable
{ {
private System.Action<AssetOperationHandle> _callback; private System.Action<AssetOperationHandle> _callback;
@@ -22,7 +23,7 @@ namespace YooAsset
{ {
add add
{ {
if (IsValid == false) if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(AssetOperationHandle)} is invalid"); throw new System.Exception($"{nameof(AssetOperationHandle)} is invalid");
if (Provider.IsDone) if (Provider.IsDone)
value.Invoke(this); value.Invoke(this);
@@ -31,42 +32,18 @@ namespace YooAsset
} }
remove remove
{ {
if (IsValid == false) if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(AssetOperationHandle)} is invalid"); throw new System.Exception($"{nameof(AssetOperationHandle)} is invalid");
_callback -= value; _callback -= value;
} }
} }
/// <summary>
/// 资源对象
/// </summary>
public UnityEngine.Object AssetObject
{
get
{
if (IsValid == false)
return null;
return Provider.AssetObject;
}
}
/// <summary>
/// 获取资源对象
/// </summary>
/// <typeparam name="TAsset">资源类型</typeparam>
public TAsset GetAssetObject<TAsset>() where TAsset : UnityEngine.Object
{
if (IsValid == false)
return null;
return Provider.AssetObject as TAsset;
}
/// <summary> /// <summary>
/// 等待异步执行完毕 /// 等待异步执行完毕
/// </summary> /// </summary>
public void WaitForAsyncComplete() public void WaitForAsyncComplete()
{ {
if (IsValid == false) if (IsValidWithWarning == false)
return; return;
Provider.WaitForAsyncComplete(); Provider.WaitForAsyncComplete();
} }
@@ -79,6 +56,38 @@ namespace YooAsset
this.ReleaseInternal(); this.ReleaseInternal();
} }
/// <summary>
/// 释放资源句柄
/// </summary>
public void Dispose()
{
this.ReleaseInternal();
}
/// <summary>
/// 资源对象
/// </summary>
public UnityEngine.Object AssetObject
{
get
{
if (IsValidWithWarning == false)
return null;
return Provider.AssetObject;
}
}
/// <summary>
/// 获取资源对象
/// </summary>
/// <typeparam name="TAsset">资源类型</typeparam>
public TAsset GetAssetObject<TAsset>() where TAsset : UnityEngine.Object
{
if (IsValidWithWarning == false)
return null;
return Provider.AssetObject as TAsset;
}
/// <summary> /// <summary>
/// 同步初始化游戏对象 /// 同步初始化游戏对象
@@ -124,7 +133,7 @@ namespace YooAsset
private GameObject InstantiateSyncInternal(Vector3 position, Quaternion rotation, Transform parent) private GameObject InstantiateSyncInternal(Vector3 position, Quaternion rotation, Transform parent)
{ {
if (IsValid == false) if (IsValidWithWarning == false)
return null; return null;
if (Provider.AssetObject == null) if (Provider.AssetObject == null)
return null; return null;

View File

@@ -1,4 +1,5 @@
using System.Collections; using System;
using System.Collections;
namespace YooAsset namespace YooAsset
{ {
@@ -14,7 +15,6 @@ namespace YooAsset
} }
internal abstract void InvokeCallback(); internal abstract void InvokeCallback();
/// <summary> /// <summary>
/// 获取资源信息 /// 获取资源信息
/// </summary> /// </summary>
@@ -23,6 +23,18 @@ namespace YooAsset
return _assetInfo; return _assetInfo;
} }
/// <summary>
/// 获取下载报告
/// </summary>
public DownloadReport GetDownloadReport()
{
if (IsValidWithWarning == false)
{
return DownloadReport.CreateDefaultReport();
}
return Provider.GetDownloadReport();
}
/// <summary> /// <summary>
/// 当前状态 /// 当前状态
/// </summary> /// </summary>
@@ -30,11 +42,11 @@ namespace YooAsset
{ {
get get
{ {
if (IsValid == false) if (IsValidWithWarning == false)
return EOperationStatus.None; return EOperationStatus.None;
if (Provider.Status == ProviderBase.EStatus.Fail) if (Provider.Status == ProviderBase.EStatus.Failed)
return EOperationStatus.Failed; return EOperationStatus.Failed;
else if (Provider.Status == ProviderBase.EStatus.Success) else if (Provider.Status == ProviderBase.EStatus.Succeed)
return EOperationStatus.Succeed; return EOperationStatus.Succeed;
else else
return EOperationStatus.None; return EOperationStatus.None;
@@ -48,7 +60,7 @@ namespace YooAsset
{ {
get get
{ {
if (IsValid == false) if (IsValidWithWarning == false)
return string.Empty; return string.Empty;
return Provider.LastError; return Provider.LastError;
} }
@@ -61,7 +73,7 @@ namespace YooAsset
{ {
get get
{ {
if (IsValid == false) if (IsValidWithWarning == false)
return 0; return 0;
return Provider.Progress; return Provider.Progress;
} }
@@ -74,7 +86,7 @@ namespace YooAsset
{ {
get get
{ {
if (IsValid == false) if (IsValidWithWarning == false)
return false; return false;
return Provider.IsDone; return Provider.IsDone;
} }
@@ -84,6 +96,20 @@ namespace YooAsset
/// 句柄是否有效 /// 句柄是否有效
/// </summary> /// </summary>
public bool IsValid public bool IsValid
{
get
{
if (Provider != null && Provider.IsDestroyed == false)
return true;
else
return false;
}
}
/// <summary>
/// 句柄是否有效
/// </summary>
internal bool IsValidWithWarning
{ {
get get
{ {
@@ -102,26 +128,12 @@ namespace YooAsset
} }
} }
/// <summary>
/// 句柄是否有效
/// </summary>
public bool IsValidNoWarning
{
get
{
if (Provider != null && Provider.IsDestroyed == false)
return true;
else
return false;
}
}
/// <summary> /// <summary>
/// 释放句柄 /// 释放句柄
/// </summary> /// </summary>
internal void ReleaseInternal() internal void ReleaseInternal()
{ {
if (IsValid == false) if (IsValidWithWarning == false)
return; return;
Provider.ReleaseHandle(this); Provider.ReleaseHandle(this);
Provider = null; Provider = null;

View File

@@ -0,0 +1,104 @@
using System;
using System.IO;
using System.Text;
namespace YooAsset
{
public class RawFileOperationHandle : OperationHandleBase, IDisposable
{
private System.Action<RawFileOperationHandle> _callback;
internal RawFileOperationHandle(ProviderBase provider) : base(provider)
{
}
internal override void InvokeCallback()
{
_callback?.Invoke(this);
}
/// <summary>
/// 完成委托
/// </summary>
public event System.Action<RawFileOperationHandle> Completed
{
add
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(RawFileOperationHandle)} is invalid");
if (Provider.IsDone)
value.Invoke(this);
else
_callback += value;
}
remove
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(RawFileOperationHandle)} is invalid");
_callback -= value;
}
}
/// <summary>
/// 等待异步执行完毕
/// </summary>
public void WaitForAsyncComplete()
{
if (IsValidWithWarning == false)
return;
Provider.WaitForAsyncComplete();
}
/// <summary>
/// 释放资源句柄
/// </summary>
public void Release()
{
this.ReleaseInternal();
}
/// <summary>
/// 释放资源句柄
/// </summary>
public void Dispose()
{
this.ReleaseInternal();
}
/// <summary>
/// 获取原生文件的二进制数据
/// </summary>
public byte[] GetRawFileData()
{
if (IsValidWithWarning == false)
return null;
string filePath = Provider.RawFilePath;
if (File.Exists(filePath) == false)
return null;
return File.ReadAllBytes(filePath);
}
/// <summary>
/// 获取原生文件的文本数据
/// </summary>
public string GetRawFileText()
{
if (IsValidWithWarning == false)
return null;
string filePath = Provider.RawFilePath;
if (File.Exists(filePath) == false)
return null;
return File.ReadAllText(filePath, Encoding.UTF8);
}
/// <summary>
/// 获取原生文件的路径
/// </summary>
public string GetRawFilePath()
{
if (IsValidWithWarning == false)
return string.Empty;
return Provider.RawFilePath;
}
}
}

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: e26f14db9addb4c49b4f0f520bf75d9d guid: e8420ba734d425a4ba9f19173d74503c
MonoImporter: MonoImporter:
externalObjects: {} externalObjects: {}
serializedVersion: 2 serializedVersion: 2

View File

@@ -3,8 +3,9 @@
namespace YooAsset namespace YooAsset
{ {
public class SceneOperationHandle : OperationHandleBase public class SceneOperationHandle : OperationHandleBase
{ {
private System.Action<SceneOperationHandle> _callback; private System.Action<SceneOperationHandle> _callback;
internal string PackageName { set; get; }
internal SceneOperationHandle(ProviderBase provider) : base(provider) internal SceneOperationHandle(ProviderBase provider) : base(provider)
{ {
@@ -21,7 +22,7 @@ namespace YooAsset
{ {
add add
{ {
if (IsValid == false) if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(SceneOperationHandle)} is invalid"); throw new System.Exception($"{nameof(SceneOperationHandle)} is invalid");
if (Provider.IsDone) if (Provider.IsDone)
value.Invoke(this); value.Invoke(this);
@@ -30,7 +31,7 @@ namespace YooAsset
} }
remove remove
{ {
if (IsValid == false) if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(SceneOperationHandle)} is invalid"); throw new System.Exception($"{nameof(SceneOperationHandle)} is invalid");
_callback -= value; _callback -= value;
} }
@@ -43,7 +44,7 @@ namespace YooAsset
{ {
get get
{ {
if (IsValid == false) if (IsValidWithWarning == false)
return new Scene(); return new Scene();
return Provider.SceneObject; return Provider.SceneObject;
} }
@@ -54,7 +55,7 @@ namespace YooAsset
/// </summary> /// </summary>
public bool ActivateScene() public bool ActivateScene()
{ {
if (IsValid == false) if (IsValidWithWarning == false)
return false; return false;
if (SceneObject.IsValid() && SceneObject.isLoaded) if (SceneObject.IsValid() && SceneObject.isLoaded)
@@ -73,7 +74,7 @@ namespace YooAsset
/// </summary> /// </summary>
public bool IsMainScene() public bool IsMainScene()
{ {
if (IsValid == false) if (IsValidWithWarning == false)
return false; return false;
if (Provider is DatabaseSceneProvider) if (Provider is DatabaseSceneProvider)
@@ -98,7 +99,7 @@ namespace YooAsset
public UnloadSceneOperation UnloadAsync() public UnloadSceneOperation UnloadAsync()
{ {
// 如果句柄无效 // 如果句柄无效
if (IsValid == false) if (IsValidWithWarning == false)
{ {
string error = $"{nameof(SceneOperationHandle)} is invalid."; string error = $"{nameof(SceneOperationHandle)} is invalid.";
var operation = new UnloadSceneOperation(error); var operation = new UnloadSceneOperation(error);

View File

@@ -1,8 +1,9 @@
using System.Collections.Generic; using System;
using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
public sealed class SubAssetsOperationHandle : OperationHandleBase public sealed class SubAssetsOperationHandle : OperationHandleBase, IDisposable
{ {
private System.Action<SubAssetsOperationHandle> _callback; private System.Action<SubAssetsOperationHandle> _callback;
@@ -21,7 +22,7 @@ namespace YooAsset
{ {
add add
{ {
if (IsValid == false) if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(SubAssetsOperationHandle)} is invalid"); throw new System.Exception($"{nameof(SubAssetsOperationHandle)} is invalid");
if (Provider.IsDone) if (Provider.IsDone)
value.Invoke(this); value.Invoke(this);
@@ -30,31 +31,18 @@ namespace YooAsset
} }
remove remove
{ {
if (IsValid == false) if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(SubAssetsOperationHandle)} is invalid"); throw new System.Exception($"{nameof(SubAssetsOperationHandle)} is invalid");
_callback -= value; _callback -= value;
} }
} }
/// <summary>
/// 子资源对象集合
/// </summary>
public UnityEngine.Object[] AllAssetObjects
{
get
{
if (IsValid == false)
return null;
return Provider.AllAssetObjects;
}
}
/// <summary> /// <summary>
/// 等待异步执行完毕 /// 等待异步执行完毕
/// </summary> /// </summary>
public void WaitForAsyncComplete() public void WaitForAsyncComplete()
{ {
if (IsValid == false) if (IsValidWithWarning == false)
return; return;
Provider.WaitForAsyncComplete(); Provider.WaitForAsyncComplete();
} }
@@ -67,6 +55,27 @@ namespace YooAsset
this.ReleaseInternal(); this.ReleaseInternal();
} }
/// <summary>
/// 释放资源句柄
/// </summary>
public void Dispose()
{
this.ReleaseInternal();
}
/// <summary>
/// 子资源对象集合
/// </summary>
public UnityEngine.Object[] AllAssetObjects
{
get
{
if (IsValidWithWarning == false)
return null;
return Provider.AllAssetObjects;
}
}
/// <summary> /// <summary>
/// 获取子资源对象 /// 获取子资源对象
@@ -75,7 +84,7 @@ namespace YooAsset
/// <param name="assetName">子资源对象名称</param> /// <param name="assetName">子资源对象名称</param>
public TObject GetSubAssetObject<TObject>(string assetName) where TObject : UnityEngine.Object public TObject GetSubAssetObject<TObject>(string assetName) where TObject : UnityEngine.Object
{ {
if (IsValid == false) if (IsValidWithWarning == false)
return null; return null;
foreach (var assetObject in Provider.AllAssetObjects) foreach (var assetObject in Provider.AllAssetObjects)
@@ -94,7 +103,7 @@ namespace YooAsset
/// <typeparam name="TObject">子资源对象类型</typeparam> /// <typeparam name="TObject">子资源对象类型</typeparam>
public TObject[] GetSubAssetObjects<TObject>() where TObject : UnityEngine.Object public TObject[] GetSubAssetObjects<TObject>() where TObject : UnityEngine.Object
{ {
if (IsValid == false) if (IsValidWithWarning == false)
return null; return null;
List<TObject> ret = new List<TObject>(Provider.AllAssetObjects.Length); List<TObject> ret = new List<TObject>(Provider.AllAssetObjects.Length);

View File

@@ -6,24 +6,27 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal sealed class AssetBundleFileLoader : AssetBundleLoaderBase internal sealed class AssetBundleFileLoader : BundleLoaderBase
{ {
private enum ESteps private enum ESteps
{ {
None = 0, None = 0,
Download, Download,
CheckDownload, CheckDownload,
Unpack,
CheckUnpack,
LoadFile, LoadFile,
CheckLoadFile, CheckLoadFile,
Done, Done,
} }
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
private string _fileLoadPath;
private bool _isWaitForAsyncComplete = false; private bool _isWaitForAsyncComplete = false;
private bool _isShowWaitForAsyncError = false; private bool _isShowWaitForAsyncError = false;
private DownloaderBase _unpacker;
private DownloaderBase _downloader; private DownloaderBase _downloader;
private AssetBundleCreateRequest _createRequest; private AssetBundleCreateRequest _createRequest;
private FileStream _fileStream;
public AssetBundleFileLoader(AssetSystemImpl impl, BundleInfo bundleInfo) : base(impl, bundleInfo) public AssetBundleFileLoader(AssetSystemImpl impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
@@ -43,17 +46,31 @@ namespace YooAsset
if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote) if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
{ {
_steps = ESteps.Download; _steps = ESteps.Download;
_fileLoadPath = MainBundleInfo.Bundle.CachedFilePath; FileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
} }
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming) else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{ {
#if UNITY_ANDROID
EBundleLoadMethod loadMethod = (EBundleLoadMethod)MainBundleInfo.Bundle.LoadMethod;
if (loadMethod == EBundleLoadMethod.LoadFromMemory || loadMethod == EBundleLoadMethod.LoadFromStream)
{
_steps = ESteps.Unpack;
FileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
}
else
{
_steps = ESteps.LoadFile;
FileLoadPath = MainBundleInfo.Bundle.StreamingFilePath;
}
#else
_steps = ESteps.LoadFile; _steps = ESteps.LoadFile;
_fileLoadPath = MainBundleInfo.Bundle.StreamingFilePath; FileLoadPath = MainBundleInfo.Bundle.StreamingFilePath;
#endif
} }
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache) else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{ {
_steps = ESteps.LoadFile; _steps = ESteps.LoadFile;
_fileLoadPath = MainBundleInfo.Bundle.CachedFilePath; FileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
} }
else else
{ {
@@ -72,6 +89,8 @@ namespace YooAsset
// 2. 检测服务器下载结果 // 2. 检测服务器下载结果
if (_steps == ESteps.CheckDownload) if (_steps == ESteps.CheckDownload)
{ {
DownloadProgress = _downloader.DownloadProgress;
DownloadedBytes = _downloader.DownloadedBytes;
if (_downloader.IsDone() == false) if (_downloader.IsDone() == false)
return; return;
@@ -87,47 +106,112 @@ namespace YooAsset
} }
} }
// 3. 加载AssetBundle // 3. 内置文件解压
if (_steps == ESteps.Unpack)
{
int failedTryAgain = 1;
var bundleInfo = PatchManifestTools.GetUnpackInfo(MainBundleInfo.Bundle);
_unpacker = DownloadSystem.BeginDownload(bundleInfo, failedTryAgain);
_steps = ESteps.CheckUnpack;
}
// 4.检测内置文件解压结果
if (_steps == ESteps.CheckUnpack)
{
DownloadProgress = _unpacker.DownloadProgress;
DownloadedBytes = _unpacker.DownloadedBytes;
if (_unpacker.IsDone() == false)
return;
if (_unpacker.HasError())
{
_steps = ESteps.Done;
Status = EStatus.Failed;
LastError = _unpacker.GetLastError();
}
else
{
_steps = ESteps.LoadFile;
}
}
// 5. 加载AssetBundle
if (_steps == ESteps.LoadFile) if (_steps == ESteps.LoadFile)
{ {
#if UNITY_EDITOR #if UNITY_EDITOR
// 注意Unity2017.4编辑器模式下如果AssetBundle文件不存在会导致编辑器崩溃这里做了预判。 // 注意Unity2017.4编辑器模式下如果AssetBundle文件不存在会导致编辑器崩溃这里做了预判。
if (System.IO.File.Exists(_fileLoadPath) == false) if (System.IO.File.Exists(FileLoadPath) == false)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EStatus.Failed; Status = EStatus.Failed;
LastError = $"Not found assetBundle file : {_fileLoadPath}"; LastError = $"Not found assetBundle file : {FileLoadPath}";
YooLogger.Error(LastError); YooLogger.Error(LastError);
return; return;
} }
#endif #endif
// Load assetBundle file // 设置下载进度
if (MainBundleInfo.Bundle.IsEncrypted) DownloadProgress = 1f;
{ DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize;
if (Impl.DecryptionServices == null)
throw new Exception($"{nameof(AssetBundleFileLoader)} need {nameof(IDecryptionServices)} : {MainBundleInfo.Bundle.BundleName}");
DecryptionFileInfo fileInfo = new DecryptionFileInfo(); // Load assetBundle file
fileInfo.BundleName = MainBundleInfo.Bundle.BundleName; var loadMethod = (EBundleLoadMethod)MainBundleInfo.Bundle.LoadMethod;
fileInfo.FileHash = MainBundleInfo.Bundle.FileHash; if (loadMethod == EBundleLoadMethod.Normal)
ulong offset = Impl.DecryptionServices.GetFileOffset(fileInfo); {
if (_isWaitForAsyncComplete) if (_isWaitForAsyncComplete)
CacheBundle = AssetBundle.LoadFromFile(_fileLoadPath, 0, offset); CacheBundle = AssetBundle.LoadFromFile(FileLoadPath);
else else
_createRequest = AssetBundle.LoadFromFileAsync(_fileLoadPath, 0, offset); _createRequest = AssetBundle.LoadFromFileAsync(FileLoadPath);
} }
else else
{ {
if (_isWaitForAsyncComplete) if (Impl.DecryptionServices == null)
CacheBundle = AssetBundle.LoadFromFile(_fileLoadPath); {
_steps = ESteps.Done;
Status = EStatus.Failed;
LastError = $"{nameof(IDecryptionServices)} is null : {MainBundleInfo.Bundle.BundleName}";
YooLogger.Error(LastError);
return;
}
DecryptFileInfo fileInfo = new DecryptFileInfo();
fileInfo.BundleName = MainBundleInfo.Bundle.BundleName;
fileInfo.FilePath = FileLoadPath;
if (loadMethod == EBundleLoadMethod.LoadFromFileOffset)
{
ulong offset = Impl.DecryptionServices.LoadFromFileOffset(fileInfo);
if (_isWaitForAsyncComplete)
CacheBundle = AssetBundle.LoadFromFile(FileLoadPath, 0, offset);
else
_createRequest = AssetBundle.LoadFromFileAsync(FileLoadPath, 0, offset);
}
else if (loadMethod == EBundleLoadMethod.LoadFromMemory)
{
byte[] fileData = Impl.DecryptionServices.LoadFromMemory(fileInfo);
if (_isWaitForAsyncComplete)
CacheBundle = AssetBundle.LoadFromMemory(fileData);
else
_createRequest = AssetBundle.LoadFromMemoryAsync(fileData);
}
else if (loadMethod == EBundleLoadMethod.LoadFromStream)
{
_fileStream = Impl.DecryptionServices.LoadFromStream(fileInfo);
uint managedReadBufferSize = Impl.DecryptionServices.GetManagedReadBufferSize();
if (_isWaitForAsyncComplete)
CacheBundle = AssetBundle.LoadFromStream(_fileStream, 0, managedReadBufferSize);
else
_createRequest = AssetBundle.LoadFromStreamAsync(_fileStream, 0, managedReadBufferSize);
}
else else
_createRequest = AssetBundle.LoadFromFileAsync(_fileLoadPath); {
throw new System.NotImplementedException();
}
} }
_steps = ESteps.CheckLoadFile; _steps = ESteps.CheckLoadFile;
} }
// 4. 检测AssetBundle加载结果 // 6. 检测AssetBundle加载结果
if (_steps == ESteps.CheckLoadFile) if (_steps == ESteps.CheckLoadFile)
{ {
if (_createRequest != null) if (_createRequest != null)
@@ -177,6 +261,21 @@ namespace YooAsset
} }
} }
/// <summary>
/// 销毁
/// </summary>
public override void Destroy(bool forceDestroy)
{
base.Destroy(forceDestroy);
if (_fileStream != null)
{
_fileStream.Close();
_fileStream.Dispose();
_fileStream = null;
}
}
/// <summary> /// <summary>
/// 主线程等待异步操作完毕 /// 主线程等待异步操作完毕
/// </summary> /// </summary>
@@ -187,6 +286,14 @@ namespace YooAsset
int frame = 1000; int frame = 1000;
while (true) while (true)
{ {
// 文件解压
if (_unpacker != null)
{
_unpacker.Update();
if (_unpacker.IsDone() == false)
continue;
}
// 保险机制 // 保险机制
// 注意如果需要从WEB端下载资源可能会触发保险机制 // 注意如果需要从WEB端下载资源可能会触发保险机制
frame--; frame--;

View File

@@ -7,7 +7,7 @@ using UnityEngine.Networking;
namespace YooAsset namespace YooAsset
{ {
internal sealed class AssetBundleWebLoader : AssetBundleLoaderBase internal sealed class AssetBundleWebLoader : BundleLoaderBase
{ {
private enum ESteps private enum ESteps
{ {
@@ -17,20 +17,19 @@ namespace YooAsset
LoadCacheFile, LoadCacheFile,
CheckLoadCacheFile, CheckLoadCacheFile,
LoadWebFile, LoadWebFile,
CheckLoadWebFile, CheckLoadWebFile,
TryLoadWebFile, TryLoadWebFile,
Done, Done,
} }
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
private float _tryTimer = 0; private float _tryTimer = 0;
private string _fileLoadPath;
private bool _isShowWaitForAsyncError = false; private bool _isShowWaitForAsyncError = false;
private DownloaderBase _downloader; private DownloaderBase _downloader;
private UnityWebRequest _webRequest; private UnityWebRequest _webRequest;
private AssetBundleCreateRequest _createRequest; private AssetBundleCreateRequest _createRequest;
public AssetBundleWebLoader(AssetSystemImpl impl, BundleInfo bundleInfo) : base(impl, bundleInfo) public AssetBundleWebLoader(AssetSystemImpl impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
{ {
} }
@@ -48,17 +47,17 @@ namespace YooAsset
if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote) if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
{ {
_steps = ESteps.Download; _steps = ESteps.Download;
_fileLoadPath = MainBundleInfo.Bundle.CachedFilePath; FileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
} }
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming) else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{ {
_steps = ESteps.LoadWebFile; _steps = ESteps.LoadWebFile;
_fileLoadPath = MainBundleInfo.Bundle.StreamingFilePath; FileLoadPath = MainBundleInfo.Bundle.StreamingFilePath;
} }
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache) else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{ {
_steps = ESteps.LoadCacheFile; _steps = ESteps.LoadCacheFile;
_fileLoadPath = MainBundleInfo.Bundle.CachedFilePath; FileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
} }
else else
{ {
@@ -77,6 +76,8 @@ namespace YooAsset
// 2. 检测服务器下载结果 // 2. 检测服务器下载结果
if (_steps == ESteps.CheckDownload) if (_steps == ESteps.CheckDownload)
{ {
DownloadProgress = _downloader.DownloadProgress;
DownloadedBytes = _downloader.DownloadedBytes;
if (_downloader.IsDone() == false) if (_downloader.IsDone() == false)
return; return;
@@ -97,31 +98,33 @@ namespace YooAsset
{ {
#if UNITY_EDITOR #if UNITY_EDITOR
// 注意Unity2017.4编辑器模式下如果AssetBundle文件不存在会导致编辑器崩溃这里做了预判。 // 注意Unity2017.4编辑器模式下如果AssetBundle文件不存在会导致编辑器崩溃这里做了预判。
if (System.IO.File.Exists(_fileLoadPath) == false) if (System.IO.File.Exists(FileLoadPath) == false)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EStatus.Failed; Status = EStatus.Failed;
LastError = $"Not found assetBundle file : {_fileLoadPath}"; LastError = $"Not found assetBundle file : {FileLoadPath}";
YooLogger.Error(LastError); YooLogger.Error(LastError);
return; return;
} }
#endif #endif
// Load assetBundle file // 设置下载进度
if (MainBundleInfo.Bundle.IsEncrypted) DownloadProgress = 1f;
{ DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize;
if (Impl.DecryptionServices == null)
throw new Exception($"{nameof(AssetBundleFileLoader)} need {nameof(IDecryptionServices)} : {MainBundleInfo.Bundle.BundleName}");
DecryptionFileInfo fileInfo = new DecryptionFileInfo(); // Load assetBundle file
fileInfo.BundleName = MainBundleInfo.Bundle.BundleName; var loadMethod = (EBundleLoadMethod)MainBundleInfo.Bundle.LoadMethod;
fileInfo.FileHash = MainBundleInfo.Bundle.FileHash; if (loadMethod == EBundleLoadMethod.Normal)
ulong offset = Impl.DecryptionServices.GetFileOffset(fileInfo); {
_createRequest = AssetBundle.LoadFromFileAsync(_fileLoadPath, 0, offset); _createRequest = AssetBundle.LoadFromFileAsync(FileLoadPath);
} }
else else
{ {
_createRequest = AssetBundle.LoadFromFileAsync(_fileLoadPath); _steps = ESteps.Done;
Status = EStatus.Failed;
LastError = $"WebGL not support encrypted bundle file : {MainBundleInfo.Bundle.BundleName}";
YooLogger.Error(LastError);
return;
} }
_steps = ESteps.CheckLoadCacheFile; _steps = ESteps.CheckLoadCacheFile;
} }
@@ -165,7 +168,8 @@ namespace YooAsset
// 5. 从WEB网站获取AssetBundle文件 // 5. 从WEB网站获取AssetBundle文件
if (_steps == ESteps.LoadWebFile) if (_steps == ESteps.LoadWebFile)
{ {
_webRequest = UnityWebRequestAssetBundle.GetAssetBundle(_fileLoadPath, Hash128.Parse(MainBundleInfo.Bundle.FileHash)); var hash = Hash128.Parse(MainBundleInfo.Bundle.FileHash);
_webRequest = UnityWebRequestAssetBundle.GetAssetBundle(FileLoadPath, hash);
_webRequest.SendWebRequest(); _webRequest.SendWebRequest();
_steps = ESteps.CheckLoadWebFile; _steps = ESteps.CheckLoadWebFile;
} }
@@ -173,6 +177,8 @@ namespace YooAsset
// 6. 检测AssetBundle加载结果 // 6. 检测AssetBundle加载结果
if (_steps == ESteps.CheckLoadWebFile) if (_steps == ESteps.CheckLoadWebFile)
{ {
DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = _webRequest.downloadedBytes;
if (_webRequest.isDone == false) if (_webRequest.isDone == false)
return; return;
@@ -182,7 +188,7 @@ namespace YooAsset
if (_webRequest.isNetworkError || _webRequest.isHttpError) if (_webRequest.isNetworkError || _webRequest.isHttpError)
#endif #endif
{ {
YooLogger.Warning($"Failed to get asset bundle from web : {_fileLoadPath} Error : {_webRequest.error}"); YooLogger.Warning($"Failed to get asset bundle from web : {FileLoadPath} Error : {_webRequest.error}");
_steps = ESteps.TryLoadWebFile; _steps = ESteps.TryLoadWebFile;
_tryTimer = 0; _tryTimer = 0;
} }

View File

@@ -5,7 +5,7 @@ using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
internal abstract class AssetBundleLoaderBase internal abstract class BundleLoaderBase
{ {
public enum EStatus public enum EStatus
{ {
@@ -18,7 +18,7 @@ namespace YooAsset
/// 所属资源系统 /// 所属资源系统
/// </summary> /// </summary>
public AssetSystemImpl Impl { private set; get; } public AssetSystemImpl Impl { private set; get; }
/// <summary> /// <summary>
/// 资源包文件信息 /// 资源包文件信息
/// </summary> /// </summary>
@@ -46,9 +46,12 @@ namespace YooAsset
private readonly List<ProviderBase> _providers = new List<ProviderBase>(100); private readonly List<ProviderBase> _providers = new List<ProviderBase>(100);
internal AssetBundle CacheBundle { set; get; } internal AssetBundle CacheBundle { set; get; }
internal string FileLoadPath { set; get; }
internal float DownloadProgress { set; get; }
internal ulong DownloadedBytes { set; get; }
public AssetBundleLoaderBase(AssetSystemImpl impl, BundleInfo bundleInfo) public BundleLoaderBase(AssetSystemImpl impl, BundleInfo bundleInfo)
{ {
Impl = impl; Impl = impl;
MainBundleInfo = bundleInfo; MainBundleInfo = bundleInfo;
@@ -81,34 +84,6 @@ namespace YooAsset
RefCount--; RefCount--;
} }
/// <summary>
/// 轮询更新
/// </summary>
public abstract void Update();
/// <summary>
/// 销毁
/// </summary>
public void Destroy(bool forceDestroy)
{
IsDestroyed = true;
// Check fatal
if (forceDestroy == false)
{
if (RefCount > 0)
throw new Exception($"Bundle file loader ref is not zero : {MainBundleInfo.Bundle.BundleName}");
if (IsDone() == false)
throw new Exception($"Bundle file loader is not done : {MainBundleInfo.Bundle.BundleName}");
}
if (CacheBundle != null)
{
CacheBundle.Unload(true);
CacheBundle = null;
}
}
/// <summary> /// <summary>
/// 是否完毕(无论成功或失败) /// 是否完毕(无论成功或失败)
/// </summary> /// </summary>
@@ -158,6 +133,35 @@ namespace YooAsset
_providers.Clear(); _providers.Clear();
} }
/// <summary>
/// 轮询更新
/// </summary>
public abstract void Update();
/// <summary>
/// 销毁
/// </summary>
public virtual void Destroy(bool forceDestroy)
{
IsDestroyed = true;
// Check fatal
if (forceDestroy == false)
{
if (RefCount > 0)
throw new Exception($"Bundle file loader ref is not zero : {MainBundleInfo.Bundle.BundleName}");
if (IsDone() == false)
throw new Exception($"Bundle file loader is not done : {MainBundleInfo.Bundle.BundleName}");
}
if (CacheBundle != null)
{
CacheBundle.Unload(true);
CacheBundle = null;
}
}
/// <summary> /// <summary>
/// 主线程等待异步操作完毕 /// 主线程等待异步操作完毕
/// </summary> /// </summary>

View File

@@ -9,12 +9,12 @@ namespace YooAsset
/// <summary> /// <summary>
/// 依赖的资源包加载器列表 /// 依赖的资源包加载器列表
/// </summary> /// </summary>
private readonly List<AssetBundleLoaderBase> _dependBundles; internal readonly List<BundleLoaderBase> DependBundles;
public DependAssetBundleGroup(List<AssetBundleLoaderBase> dpendBundles) public DependAssetBundleGroup(List<BundleLoaderBase> dpendBundles)
{ {
_dependBundles = dpendBundles; DependBundles = dpendBundles;
} }
/// <summary> /// <summary>
@@ -22,7 +22,7 @@ namespace YooAsset
/// </summary> /// </summary>
public bool IsDone() public bool IsDone()
{ {
foreach (var loader in _dependBundles) foreach (var loader in DependBundles)
{ {
if (loader.IsDone() == false) if (loader.IsDone() == false)
return false; return false;
@@ -35,9 +35,9 @@ namespace YooAsset
/// </summary> /// </summary>
public bool IsSucceed() public bool IsSucceed()
{ {
foreach (var loader in _dependBundles) foreach (var loader in DependBundles)
{ {
if (loader.Status != AssetBundleLoaderBase.EStatus.Succeed) if (loader.Status != BundleLoaderBase.EStatus.Succeed)
{ {
return false; return false;
} }
@@ -50,9 +50,9 @@ namespace YooAsset
/// </summary> /// </summary>
public string GetLastError() public string GetLastError()
{ {
foreach (var loader in _dependBundles) foreach (var loader in DependBundles)
{ {
if (loader.Status != AssetBundleLoaderBase.EStatus.Succeed) if (loader.Status != BundleLoaderBase.EStatus.Succeed)
{ {
return loader.LastError; return loader.LastError;
} }
@@ -65,7 +65,7 @@ namespace YooAsset
/// </summary> /// </summary>
public void WaitForAsyncComplete() public void WaitForAsyncComplete()
{ {
foreach (var loader in _dependBundles) foreach (var loader in DependBundles)
{ {
if (loader.IsDone() == false) if (loader.IsDone() == false)
loader.WaitForAsyncComplete(); loader.WaitForAsyncComplete();
@@ -77,7 +77,7 @@ namespace YooAsset
/// </summary> /// </summary>
public void Reference() public void Reference()
{ {
foreach (var loader in _dependBundles) foreach (var loader in DependBundles)
{ {
loader.Reference(); loader.Reference();
} }
@@ -88,7 +88,7 @@ namespace YooAsset
/// </summary> /// </summary>
public void Release() public void Release()
{ {
foreach (var loader in _dependBundles) foreach (var loader in DependBundles)
{ {
loader.Release(); loader.Release();
} }
@@ -99,12 +99,12 @@ namespace YooAsset
/// </summary> /// </summary>
internal void GetBundleDebugInfos(List<DebugBundleInfo> output) internal void GetBundleDebugInfos(List<DebugBundleInfo> output)
{ {
foreach (var loader in _dependBundles) foreach (var loader in DependBundles)
{ {
var bundleInfo = new DebugBundleInfo(); var bundleInfo = new DebugBundleInfo();
bundleInfo.BundleName = loader.MainBundleInfo.Bundle.BundleName; bundleInfo.BundleName = loader.MainBundleInfo.Bundle.BundleName;
bundleInfo.RefCount = loader.RefCount; bundleInfo.RefCount = loader.RefCount;
bundleInfo.Status = (int)loader.Status; bundleInfo.Status = loader.Status.ToString();
output.Add(bundleInfo); output.Add(bundleInfo);
} }
} }

View File

@@ -0,0 +1,29 @@

namespace YooAsset
{
/// <summary>
/// Bundle文件的加载方法
/// </summary>
public enum EBundleLoadMethod
{
/// <summary>
/// 正常加载(不需要解密)
/// </summary>
Normal = 0,
/// <summary>
/// 通过文件偏移来解密加载
/// </summary>
LoadFromFileOffset = 1,
/// <summary>
/// 通过文件内存来解密加载
/// </summary>
LoadFromMemory = 2,
/// <summary>
/// 通过文件流来解密加载
/// </summary>
LoadFromStream = 3,
}
}

View File

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

View File

@@ -0,0 +1,179 @@
using System.IO;
namespace YooAsset
{
internal class RawBundleFileLoader : BundleLoaderBase
{
private enum ESteps
{
None,
Download,
CheckDownload,
Unpack,
CheckUnpack,
CheckFile,
Done,
}
private ESteps _steps = ESteps.None;
private bool _isShowWaitForAsyncError = false;
private DownloaderBase _unpacker;
private DownloaderBase _downloader;
public RawBundleFileLoader(AssetSystemImpl impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
{
}
/// <summary>
/// 轮询更新
/// </summary>
public override void Update()
{
if (_steps == ESteps.Done)
return;
if (_steps == ESteps.None)
{
if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
{
_steps = ESteps.Download;
FileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{
#if UNITY_ANDROID || UNITY_WEBGL
_steps = ESteps.Unpack;
FileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
#else
_steps = ESteps.CheckFile;
FileLoadPath = MainBundleInfo.Bundle.StreamingFilePath;
#endif
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{
_steps = ESteps.CheckFile;
FileLoadPath = MainBundleInfo.Bundle.CachedFilePath;
}
else
{
throw new System.NotImplementedException(MainBundleInfo.LoadMode.ToString());
}
}
// 1. 下载远端文件
if (_steps == ESteps.Download)
{
int failedTryAgain = int.MaxValue;
_downloader = DownloadSystem.BeginDownload(MainBundleInfo, failedTryAgain);
_steps = ESteps.CheckDownload;
}
// 2. 检测下载结果
if (_steps == ESteps.CheckDownload)
{
DownloadProgress = _downloader.DownloadProgress;
DownloadedBytes = _downloader.DownloadedBytes;
if (_downloader.IsDone() == false)
return;
if (_downloader.HasError())
{
_steps = ESteps.Done;
Status = EStatus.Failed;
LastError = _downloader.GetLastError();
}
else
{
_steps = ESteps.CheckFile;
}
}
// 3. 解压内置文件
if (_steps == ESteps.Unpack)
{
int failedTryAgain = 1;
var bundleInfo = PatchManifestTools.GetUnpackInfo(MainBundleInfo.Bundle);
_unpacker = DownloadSystem.BeginDownload(bundleInfo, failedTryAgain);
_steps = ESteps.CheckUnpack;
}
// 4. 检测解压结果
if (_steps == ESteps.CheckUnpack)
{
DownloadProgress = _unpacker.DownloadProgress;
DownloadedBytes = _unpacker.DownloadedBytes;
if (_unpacker.IsDone() == false)
return;
if (_unpacker.HasError())
{
_steps = ESteps.Done;
Status = EStatus.Failed;
LastError = _unpacker.GetLastError();
}
else
{
_steps = ESteps.CheckFile;
}
}
// 5. 检测结果
if (_steps == ESteps.CheckFile)
{
// 设置下载进度
DownloadProgress = 1f;
DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize;
_steps = ESteps.Done;
if (File.Exists(FileLoadPath))
{
Status = EStatus.Succeed;
}
else
{
Status = EStatus.Failed;
LastError = $"Raw file not found : {FileLoadPath}";
}
}
}
/// <summary>
/// 主线程等待异步操作完毕
/// </summary>
public override void WaitForAsyncComplete()
{
int frame = 1000;
while (true)
{
// 文件解压
if (_unpacker != null)
{
_unpacker.Update();
if (_unpacker.IsDone() == false)
continue;
}
// 保险机制
// 注意如果需要从WEB端下载资源可能会触发保险机制
frame--;
if (frame == 0)
{
if (_isShowWaitForAsyncError == false)
{
_isShowWaitForAsyncError = true;
YooLogger.Error($"WaitForAsyncComplete failed ! Try load bundle : {MainBundleInfo.Bundle.BundleName} from remote with sync load method !");
}
break;
}
// 驱动流程
Update();
// 完成后退出
if (IsDone())
break;
}
}
}
}

View File

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

View File

@@ -41,7 +41,7 @@ namespace YooAsset
if (_steps == ESteps.Clone) if (_steps == ESteps.Clone)
{ {
if (_handle.IsValid == false) if (_handle.IsValidWithWarning == false)
{ {
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Failed; Status = EOperationStatus.Failed;

View File

@@ -1,447 +0,0 @@
using System.IO;
namespace YooAsset
{
/// <summary>
/// 原生文件操作
/// </summary>
public abstract class RawFileOperation : AsyncOperationBase
{
internal readonly BundleInfo _bundleInfo;
/// <summary>
/// 原生文件的拷贝路径
/// </summary>
public string CopyPath { private set; get; }
internal RawFileOperation(BundleInfo bundleInfo, string copyPath)
{
_bundleInfo = bundleInfo;
CopyPath = copyPath;
}
/// <summary>
/// 原生文件的缓存路径
/// </summary>
public abstract string GetCachePath();
/// <summary>
/// 获取原生文件的二进制数据
/// </summary>
public byte[] LoadFileData()
{
string filePath = GetCachePath();
if (File.Exists(filePath) == false)
return null;
return File.ReadAllBytes(filePath);
}
/// <summary>
/// 获取原生文件的文本数据
/// </summary>
public string LoadFileText()
{
string filePath = GetCachePath();
if (File.Exists(filePath) == false)
return string.Empty;
return File.ReadAllText(filePath, System.Text.Encoding.UTF8);
}
}
/// <summary>
/// 发生错误的原生文件操作
/// </summary>
internal sealed class CompletedRawFileOperation : RawFileOperation
{
private readonly string _error;
internal CompletedRawFileOperation(string error, string copyPath) : base(null, copyPath)
{
_error = error;
}
internal override void Start()
{
Status = EOperationStatus.Failed;
Error = _error;
}
internal override void Update()
{
}
/// <summary>
/// 原生文件的缓存路径
/// </summary>
public override string GetCachePath()
{
return string.Empty;
}
}
/// <summary>
/// 编辑器下模拟运行的原生文件操作
/// </summary>
internal sealed class EditorPlayModeRawFileOperation : RawFileOperation
{
private enum ESteps
{
None,
Prepare,
CheckAndCopyFile,
Done,
}
private ESteps _steps = ESteps.None;
internal EditorPlayModeRawFileOperation(BundleInfo bundleInfo, string copyPath) : base(bundleInfo, copyPath)
{
}
internal override void Start()
{
_steps = ESteps.Prepare;
}
internal override void Update()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
// 1. 准备工作
if (_steps == ESteps.Prepare)
{
if (_bundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromEditor)
{
_steps = ESteps.CheckAndCopyFile;
return; // 模拟实现异步操作
}
else
{
throw new System.NotImplementedException(_bundleInfo.LoadMode.ToString());
}
}
// 2. 检测并拷贝原生文件
if (_steps == ESteps.CheckAndCopyFile)
{
// 如果不需要保存文件
if (string.IsNullOrEmpty(CopyPath))
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
return;
}
// 如果原生文件已经存在,则将其删除
if (File.Exists(CopyPath))
{
File.Delete(CopyPath);
}
try
{
FileUtility.CreateFileDirectory(CopyPath);
File.Copy(GetCachePath(), CopyPath, true);
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
catch (System.Exception e)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = e.ToString();
}
}
}
/// <summary>
/// 原生文件的缓存路径
/// </summary>
public override string GetCachePath()
{
if (_bundleInfo == null)
return string.Empty;
return _bundleInfo.EditorAssetPath;
}
}
/// <summary>
/// 离线模式的原生文件操作
/// </summary>
internal sealed class OfflinePlayModeRawFileOperation : RawFileOperation
{
private enum ESteps
{
None,
Prepare,
DownloadBuildinFile,
CheckDownload,
CheckAndCopyFile,
Done,
}
private ESteps _steps = ESteps.None;
private DownloaderBase _downloader;
public OfflinePlayModeRawFileOperation(BundleInfo bundleInfo, string copyPath) : base(bundleInfo, copyPath)
{
}
internal override void Start()
{
_steps = ESteps.Prepare;
}
internal override void Update()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
// 1. 准备工作
if (_steps == ESteps.Prepare)
{
if (_bundleInfo.LoadMode == BundleInfo.ELoadMode.None)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Bundle info is invalid : {_bundleInfo.Bundle.BundleName}";
}
else if (_bundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{
_steps = ESteps.DownloadBuildinFile;
}
else if (_bundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{
_steps = ESteps.CheckAndCopyFile;
}
else
{
throw new System.NotImplementedException(_bundleInfo.LoadMode.ToString());
}
}
// 2. 下载文件
if (_steps == ESteps.DownloadBuildinFile)
{
int failedTryAgain = int.MaxValue;
var bundleInfo = PatchHelper.ConvertToUnpackInfo(_bundleInfo.Bundle);
_downloader = DownloadSystem.BeginDownload(bundleInfo, failedTryAgain);
_steps = ESteps.CheckDownload;
}
// 3. 检测下载结果
if (_steps == ESteps.CheckDownload)
{
Progress = _downloader.DownloadProgress;
if (_downloader.IsDone() == false)
return;
if (_downloader.HasError())
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _downloader.GetLastError();
}
else
{
_steps = ESteps.CheckAndCopyFile;
}
}
// 4. 检测并拷贝原生文件
if (_steps == ESteps.CheckAndCopyFile)
{
// 如果不需要保存文件
if (string.IsNullOrEmpty(CopyPath))
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
return;
}
// 如果原生文件已经存在,则验证其完整性
if (File.Exists(CopyPath))
{
var verifyResult = CacheSystem.VerifyContentInternal(CopyPath, _bundleInfo.Bundle.FileSize, _bundleInfo.Bundle.FileCRC, EVerifyLevel.High);
if (verifyResult == EVerifyResult.Succeed)
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
return;
}
else
{
File.Delete(CopyPath);
}
}
try
{
FileUtility.CreateFileDirectory(CopyPath);
File.Copy(GetCachePath(), CopyPath, true);
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
catch (System.Exception e)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = e.ToString();
}
}
}
/// <summary>
/// 原生文件的缓存路径
/// </summary>
public override string GetCachePath()
{
if (_bundleInfo == null)
return string.Empty;
return _bundleInfo.Bundle.CachedFilePath;
}
}
/// <summary>
/// 联机模式的原生文件操作
/// </summary>
internal sealed class HostPlayModeRawFileOperation : RawFileOperation
{
private enum ESteps
{
None,
Prepare,
DownloadWebFile,
DownloadBuildinFile,
CheckDownload,
CheckAndCopyFile,
Done,
}
private ESteps _steps = ESteps.None;
private DownloaderBase _downloader;
internal HostPlayModeRawFileOperation(BundleInfo bundleInfo, string copyPath) : base(bundleInfo, copyPath)
{
}
internal override void Start()
{
_steps = ESteps.Prepare;
}
internal override void Update()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
// 1. 准备工作
if (_steps == ESteps.Prepare)
{
if (_bundleInfo.LoadMode == BundleInfo.ELoadMode.None)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Bundle info is invalid : {_bundleInfo.Bundle.BundleName}";
}
else if (_bundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
{
_steps = ESteps.DownloadWebFile;
}
else if (_bundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{
_steps = ESteps.DownloadBuildinFile;
}
else if (_bundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{
_steps = ESteps.CheckAndCopyFile;
}
else
{
throw new System.NotImplementedException(_bundleInfo.LoadMode.ToString());
}
}
// 2. 下载远端文件
if (_steps == ESteps.DownloadWebFile)
{
int failedTryAgain = int.MaxValue;
_downloader = DownloadSystem.BeginDownload(_bundleInfo, failedTryAgain);
_steps = ESteps.CheckDownload;
}
// 3. 下载内置文件
if (_steps == ESteps.DownloadBuildinFile)
{
int failedTryAgain = int.MaxValue;
var bundleInfo = PatchHelper.ConvertToUnpackInfo(_bundleInfo.Bundle);
_downloader = DownloadSystem.BeginDownload(bundleInfo, failedTryAgain);
_steps = ESteps.CheckDownload;
}
// 4. 检测下载结果
if (_steps == ESteps.CheckDownload)
{
Progress = _downloader.DownloadProgress;
if (_downloader.IsDone() == false)
return;
if (_downloader.HasError())
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _downloader.GetLastError();
}
else
{
_steps = ESteps.CheckAndCopyFile;
}
}
// 5. 检测并拷贝原生文件
if (_steps == ESteps.CheckAndCopyFile)
{
// 如果不需要保存文件
if (string.IsNullOrEmpty(CopyPath))
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
return;
}
// 如果原生文件已经存在,则验证其完整性
if (File.Exists(CopyPath))
{
var verifyResult = CacheSystem.VerifyContentInternal(CopyPath, _bundleInfo.Bundle.FileSize, _bundleInfo.Bundle.FileCRC, EVerifyLevel.High);
if (verifyResult == EVerifyResult.Succeed)
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
return;
}
else
{
File.Delete(CopyPath);
}
}
try
{
FileUtility.CreateFileDirectory(CopyPath);
File.Copy(GetCachePath(), CopyPath, true);
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
catch (System.Exception e)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = e.ToString();
}
}
}
/// <summary>
/// 原生文件的缓存路径
/// </summary>
public override string GetCachePath()
{
if (_bundleInfo == null)
return string.Empty;
return _bundleInfo.Bundle.CachedFilePath;
}
}
}

View File

@@ -7,21 +7,14 @@ namespace YooAsset
internal sealed class BundledAssetProvider : BundledProvider internal sealed class BundledAssetProvider : BundledProvider
{ {
private AssetBundleRequest _cacheRequest; private AssetBundleRequest _cacheRequest;
public override float Progress
{
get
{
if (_cacheRequest == null)
return 0;
return _cacheRequest.progress;
}
}
public BundledAssetProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo) : base(impl, providerGUID, assetInfo) public BundledAssetProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo) : base(impl, providerGUID, assetInfo)
{ {
} }
public override void Update() public override void Update()
{ {
DebugRecording();
if (IsDone) if (IsDone)
return; return;
@@ -46,15 +39,15 @@ namespace YooAsset
if (DependBundleGroup.IsSucceed() == false) if (DependBundleGroup.IsSucceed() == false)
{ {
Status = EStatus.Fail; Status = EStatus.Failed;
LastError = DependBundleGroup.GetLastError(); LastError = DependBundleGroup.GetLastError();
InvokeCompletion(); InvokeCompletion();
return; return;
} }
if (OwnerBundle.Status != AssetBundleLoaderBase.EStatus.Succeed) if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{ {
Status = EStatus.Fail; Status = EStatus.Failed;
LastError = OwnerBundle.LastError; LastError = OwnerBundle.LastError;
InvokeCompletion(); InvokeCompletion();
return; return;
@@ -64,8 +57,9 @@ namespace YooAsset
{ {
if (OwnerBundle.IsDestroyed) if (OwnerBundle.IsDestroyed)
throw new System.Exception("Should never get here !"); throw new System.Exception("Should never get here !");
Status = EStatus.Fail; Status = EStatus.Failed;
LastError = $"The bundle {OwnerBundle.MainBundleInfo.Bundle.BundleName} has been destroyed by unity bugs !"; LastError = $"The bundle {OwnerBundle.MainBundleInfo.Bundle.BundleName} has been destroyed by unity bugs !";
YooLogger.Error(LastError);
InvokeCompletion(); InvokeCompletion();
return; return;
} }
@@ -106,14 +100,15 @@ namespace YooAsset
} }
else else
{ {
Progress = _cacheRequest.progress;
if (_cacheRequest.isDone == false) if (_cacheRequest.isDone == false)
return; return;
AssetObject = _cacheRequest.asset; AssetObject = _cacheRequest.asset;
} }
} }
Status = AssetObject == null ? EStatus.Fail : EStatus.Success; Status = AssetObject == null ? EStatus.Failed : EStatus.Succeed;
if (Status == EStatus.Fail) if (Status == EStatus.Failed)
{ {
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
LastError = $"Failed to load asset : {MainAssetInfo.AssetPath} AssetType : null AssetBundle : {OwnerBundle.MainBundleInfo.Bundle.BundleName}"; LastError = $"Failed to load asset : {MainAssetInfo.AssetPath} AssetType : null AssetBundle : {OwnerBundle.MainBundleInfo.Bundle.BundleName}";

View File

@@ -3,12 +3,12 @@ using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
internal abstract class BundledProvider : ProviderBase internal abstract class BundledProvider : ProviderBase
{ {
protected AssetBundleLoaderBase OwnerBundle { private set; get; } protected BundleLoaderBase OwnerBundle { private set; get; }
protected DependAssetBundleGroup DependBundleGroup { private set; get; } protected DependAssetBundleGroup DependBundleGroup { private set; get; }
public BundledProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo) : base(impl, providerGUID, assetInfo) public BundledProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo) : base(impl, providerGUID, assetInfo)
{ {
OwnerBundle = impl.CreateOwnerAssetBundleLoader(assetInfo); OwnerBundle = impl.CreateOwnerAssetBundleLoader(assetInfo);
OwnerBundle.Reference(); OwnerBundle.Reference();
@@ -35,6 +35,23 @@ namespace YooAsset
} }
} }
/// <summary>
/// 获取下载报告
/// </summary>
public override DownloadReport GetDownloadReport()
{
DownloadReport result = new DownloadReport();
result.TotalSize = (ulong)OwnerBundle.MainBundleInfo.Bundle.FileSize;
result.DownloadedBytes = OwnerBundle.DownloadedBytes;
foreach (var dependBundle in DependBundleGroup.DependBundles)
{
result.TotalSize += (ulong)dependBundle.MainBundleInfo.Bundle.FileSize;
result.DownloadedBytes += dependBundle.DownloadedBytes;
}
result.Progress = result.DownloadedBytes / result.TotalSize;
return result;
}
/// <summary> /// <summary>
/// 获取资源包的调试信息列表 /// 获取资源包的调试信息列表
/// </summary> /// </summary>
@@ -43,7 +60,7 @@ namespace YooAsset
var bundleInfo = new DebugBundleInfo(); var bundleInfo = new DebugBundleInfo();
bundleInfo.BundleName = OwnerBundle.MainBundleInfo.Bundle.BundleName; bundleInfo.BundleName = OwnerBundle.MainBundleInfo.Bundle.BundleName;
bundleInfo.RefCount = OwnerBundle.RefCount; bundleInfo.RefCount = OwnerBundle.RefCount;
bundleInfo.Status = (int)OwnerBundle.Status; bundleInfo.Status = OwnerBundle.Status.ToString();
output.Add(bundleInfo); output.Add(bundleInfo);
DependBundleGroup.GetBundleDebugInfos(output); DependBundleGroup.GetBundleDebugInfos(output);

View File

@@ -0,0 +1,50 @@

namespace YooAsset
{
internal class BundledRawFileProvider : BundledProvider
{
public BundledRawFileProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo) : base(impl, providerGUID, assetInfo)
{
}
public override void Update()
{
DebugRecording();
if (IsDone)
return;
if (Status == EStatus.None)
{
Status = EStatus.CheckBundle;
}
if (Status == EStatus.CheckBundle)
{
if (IsWaitForAsyncComplete)
{
OwnerBundle.WaitForAsyncComplete();
}
if (OwnerBundle.IsDone() == false)
return;
if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{
Status = EStatus.Failed;
LastError = OwnerBundle.LastError;
InvokeCompletion();
return;
}
Status = EStatus.Checking;
}
if (Status == EStatus.Checking)
{
RawFilePath = OwnerBundle.FileLoadPath;
Status = EStatus.Succeed;
InvokeCompletion();
}
}
}
}

View File

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

View File

@@ -13,15 +13,6 @@ namespace YooAsset
private readonly bool _activateOnLoad; private readonly bool _activateOnLoad;
private readonly int _priority; private readonly int _priority;
private AsyncOperation _asyncOp; private AsyncOperation _asyncOp;
public override float Progress
{
get
{
if (_asyncOp == null)
return 0;
return _asyncOp.progress;
}
}
public BundledSceneProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo, LoadSceneMode sceneMode, bool activateOnLoad, int priority) : base(impl, providerGUID, assetInfo) public BundledSceneProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo, LoadSceneMode sceneMode, bool activateOnLoad, int priority) : base(impl, providerGUID, assetInfo)
{ {
@@ -32,6 +23,8 @@ namespace YooAsset
} }
public override void Update() public override void Update()
{ {
DebugRecording();
if (IsDone) if (IsDone)
return; return;
@@ -50,15 +43,15 @@ namespace YooAsset
if (DependBundleGroup.IsSucceed() == false) if (DependBundleGroup.IsSucceed() == false)
{ {
Status = EStatus.Fail; Status = EStatus.Failed;
LastError = DependBundleGroup.GetLastError(); LastError = DependBundleGroup.GetLastError();
InvokeCompletion(); InvokeCompletion();
return; return;
} }
if (OwnerBundle.Status != AssetBundleLoaderBase.EStatus.Succeed) if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{ {
Status = EStatus.Fail; Status = EStatus.Failed;
LastError = OwnerBundle.LastError; LastError = OwnerBundle.LastError;
InvokeCompletion(); InvokeCompletion();
return; return;
@@ -81,7 +74,7 @@ namespace YooAsset
} }
else else
{ {
Status = EStatus.Fail; Status = EStatus.Failed;
LastError = $"Failed to load scene : {_sceneName}"; LastError = $"Failed to load scene : {_sceneName}";
YooLogger.Error(LastError); YooLogger.Error(LastError);
InvokeCompletion(); InvokeCompletion();
@@ -91,13 +84,14 @@ namespace YooAsset
// 3. 检测加载结果 // 3. 检测加载结果
if (Status == EStatus.Checking) if (Status == EStatus.Checking)
{ {
Progress = _asyncOp.progress;
if (_asyncOp.isDone) if (_asyncOp.isDone)
{ {
if (SceneObject.IsValid() && _activateOnLoad) if (SceneObject.IsValid() && _activateOnLoad)
SceneManager.SetActiveScene(SceneObject); SceneManager.SetActiveScene(SceneObject);
Status = SceneObject.IsValid() ? EStatus.Success : EStatus.Fail; Status = SceneObject.IsValid() ? EStatus.Succeed : EStatus.Failed;
if(Status == EStatus.Fail) if (Status == EStatus.Failed)
{ {
LastError = $"The load scene is invalid : {MainAssetInfo.AssetPath}"; LastError = $"The load scene is invalid : {MainAssetInfo.AssetPath}";
YooLogger.Error(LastError); YooLogger.Error(LastError);

View File

@@ -7,21 +7,14 @@ namespace YooAsset
internal sealed class BundledSubAssetsProvider : BundledProvider internal sealed class BundledSubAssetsProvider : BundledProvider
{ {
private AssetBundleRequest _cacheRequest; private AssetBundleRequest _cacheRequest;
public override float Progress
{
get
{
if (_cacheRequest == null)
return 0;
return _cacheRequest.progress;
}
}
public BundledSubAssetsProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo) : base(impl, providerGUID, assetInfo) public BundledSubAssetsProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo) : base(impl, providerGUID, assetInfo)
{ {
} }
public override void Update() public override void Update()
{ {
DebugRecording();
if (IsDone) if (IsDone)
return; return;
@@ -46,15 +39,15 @@ namespace YooAsset
if (DependBundleGroup.IsSucceed() == false) if (DependBundleGroup.IsSucceed() == false)
{ {
Status = EStatus.Fail; Status = EStatus.Failed;
LastError = DependBundleGroup.GetLastError(); LastError = DependBundleGroup.GetLastError();
InvokeCompletion(); InvokeCompletion();
return; return;
} }
if (OwnerBundle.Status != AssetBundleLoaderBase.EStatus.Succeed) if (OwnerBundle.Status != BundleLoaderBase.EStatus.Succeed)
{ {
Status = EStatus.Fail; Status = EStatus.Failed;
LastError = OwnerBundle.LastError; LastError = OwnerBundle.LastError;
InvokeCompletion(); InvokeCompletion();
return; return;
@@ -96,14 +89,15 @@ namespace YooAsset
} }
else else
{ {
Progress = _cacheRequest.progress;
if (_cacheRequest.isDone == false) if (_cacheRequest.isDone == false)
return; return;
AllAssetObjects = _cacheRequest.allAssets; AllAssetObjects = _cacheRequest.allAssets;
} }
} }
Status = AllAssetObjects == null ? EStatus.Fail : EStatus.Success; Status = AllAssetObjects == null ? EStatus.Failed : EStatus.Succeed;
if (Status == EStatus.Fail) if (Status == EStatus.Failed)
{ {
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
LastError = $"Failed to load sub assets : {MainAssetInfo.AssetPath} AssetType : null AssetBundle : {OwnerBundle.MainBundleInfo.Bundle.BundleName}"; LastError = $"Failed to load sub assets : {MainAssetInfo.AssetPath} AssetType : null AssetBundle : {OwnerBundle.MainBundleInfo.Bundle.BundleName}";

View File

@@ -3,17 +3,6 @@ namespace YooAsset
{ {
internal sealed class CompletedProvider : ProviderBase internal sealed class CompletedProvider : ProviderBase
{ {
public override float Progress
{
get
{
if (IsDone)
return 1f;
else
return 0;
}
}
public CompletedProvider(AssetInfo assetInfo) : base(null, string.Empty, assetInfo) public CompletedProvider(AssetInfo assetInfo) : base(null, string.Empty, assetInfo)
{ {
} }
@@ -24,7 +13,7 @@ namespace YooAsset
{ {
if (Status == EStatus.None) if (Status == EStatus.None)
{ {
Status = EStatus.Fail; Status = EStatus.Failed;
LastError = error; LastError = error;
InvokeCompletion(); InvokeCompletion();
} }

View File

@@ -6,17 +6,6 @@ namespace YooAsset
{ {
internal sealed class DatabaseAssetProvider : ProviderBase internal sealed class DatabaseAssetProvider : ProviderBase
{ {
public override float Progress
{
get
{
if (IsDone)
return 1f;
else
return 0;
}
}
public DatabaseAssetProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo) : base(impl, providerGUID, assetInfo) public DatabaseAssetProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo) : base(impl, providerGUID, assetInfo)
{ {
} }
@@ -32,7 +21,7 @@ namespace YooAsset
string guid = UnityEditor.AssetDatabase.AssetPathToGUID(MainAssetInfo.AssetPath); string guid = UnityEditor.AssetDatabase.AssetPathToGUID(MainAssetInfo.AssetPath);
if (string.IsNullOrEmpty(guid)) if (string.IsNullOrEmpty(guid))
{ {
Status = EStatus.Fail; Status = EStatus.Failed;
LastError = $"Not found asset : {MainAssetInfo.AssetPath}"; LastError = $"Not found asset : {MainAssetInfo.AssetPath}";
YooLogger.Error(LastError); YooLogger.Error(LastError);
InvokeCompletion(); InvokeCompletion();
@@ -59,8 +48,8 @@ namespace YooAsset
// 2. 检测加载结果 // 2. 检测加载结果
if (Status == EStatus.Checking) if (Status == EStatus.Checking)
{ {
Status = AssetObject == null ? EStatus.Fail : EStatus.Success; Status = AssetObject == null ? EStatus.Failed : EStatus.Succeed;
if (Status == EStatus.Fail) if (Status == EStatus.Failed)
{ {
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
LastError = $"Failed to load asset object : {MainAssetInfo.AssetPath} AssetType : null"; LastError = $"Failed to load asset object : {MainAssetInfo.AssetPath} AssetType : null";

View File

@@ -0,0 +1,44 @@

namespace YooAsset
{
internal class DatabaseRawFileProvider : ProviderBase
{
public DatabaseRawFileProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo) : base(impl, providerGUID, assetInfo)
{
}
public override void Update()
{
#if UNITY_EDITOR
if (IsDone)
return;
if (Status == EStatus.None)
{
// 检测资源文件是否存在
string guid = UnityEditor.AssetDatabase.AssetPathToGUID(MainAssetInfo.AssetPath);
if (string.IsNullOrEmpty(guid))
{
Status = EStatus.Failed;
LastError = $"Not found asset : {MainAssetInfo.AssetPath}";
YooLogger.Error(LastError);
InvokeCompletion();
return;
}
Status = EStatus.Checking;
// 注意:模拟异步加载效果提前返回
if (IsWaitForAsyncComplete == false)
return;
}
if(Status == EStatus.Checking)
{
RawFilePath = MainAssetInfo.AssetPath;
Status = EStatus.Succeed;
InvokeCompletion();
}
#endif
}
}
}

View File

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

View File

@@ -9,15 +9,6 @@ namespace YooAsset
private readonly bool _activateOnLoad; private readonly bool _activateOnLoad;
private readonly int _priority; private readonly int _priority;
private AsyncOperation _asyncOp; private AsyncOperation _asyncOp;
public override float Progress
{
get
{
if (_asyncOp == null)
return 0;
return _asyncOp.progress;
}
}
public DatabaseSceneProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo, LoadSceneMode sceneMode, bool activateOnLoad, int priority) : base(impl, providerGUID, assetInfo) public DatabaseSceneProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo, LoadSceneMode sceneMode, bool activateOnLoad, int priority) : base(impl, providerGUID, assetInfo)
{ {
@@ -51,7 +42,7 @@ namespace YooAsset
} }
else else
{ {
Status = EStatus.Fail; Status = EStatus.Failed;
LastError = $"Failed to load scene : {MainAssetInfo.AssetPath}"; LastError = $"Failed to load scene : {MainAssetInfo.AssetPath}";
YooLogger.Error(LastError); YooLogger.Error(LastError);
InvokeCompletion(); InvokeCompletion();
@@ -61,13 +52,14 @@ namespace YooAsset
// 2. 检测加载结果 // 2. 检测加载结果
if (Status == EStatus.Checking) if (Status == EStatus.Checking)
{ {
Progress = _asyncOp.progress;
if (_asyncOp.isDone) if (_asyncOp.isDone)
{ {
if (SceneObject.IsValid() && _activateOnLoad) if (SceneObject.IsValid() && _activateOnLoad)
SceneManager.SetActiveScene(SceneObject); SceneManager.SetActiveScene(SceneObject);
Status = SceneObject.IsValid() ? EStatus.Success : EStatus.Fail; Status = SceneObject.IsValid() ? EStatus.Succeed : EStatus.Failed;
if (Status == EStatus.Fail) if (Status == EStatus.Failed)
{ {
LastError = $"The loaded scene is invalid : {MainAssetInfo.AssetPath}"; LastError = $"The loaded scene is invalid : {MainAssetInfo.AssetPath}";
YooLogger.Error(LastError); YooLogger.Error(LastError);

View File

@@ -6,17 +6,6 @@ namespace YooAsset
{ {
internal sealed class DatabaseSubAssetsProvider : ProviderBase internal sealed class DatabaseSubAssetsProvider : ProviderBase
{ {
public override float Progress
{
get
{
if (IsDone)
return 1f;
else
return 0;
}
}
public DatabaseSubAssetsProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo) : base(impl, providerGUID, assetInfo) public DatabaseSubAssetsProvider(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo) : base(impl, providerGUID, assetInfo)
{ {
} }
@@ -32,7 +21,7 @@ namespace YooAsset
string guid = UnityEditor.AssetDatabase.AssetPathToGUID(MainAssetInfo.AssetPath); string guid = UnityEditor.AssetDatabase.AssetPathToGUID(MainAssetInfo.AssetPath);
if (string.IsNullOrEmpty(guid)) if (string.IsNullOrEmpty(guid))
{ {
Status = EStatus.Fail; Status = EStatus.Failed;
LastError = $"Not found asset : {MainAssetInfo.AssetPath}"; LastError = $"Not found asset : {MainAssetInfo.AssetPath}";
YooLogger.Error(LastError); YooLogger.Error(LastError);
InvokeCompletion(); InvokeCompletion();
@@ -70,8 +59,8 @@ namespace YooAsset
// 2. 检测加载结果 // 2. 检测加载结果
if (Status == EStatus.Checking) if (Status == EStatus.Checking)
{ {
Status = AllAssetObjects == null ? EStatus.Fail : EStatus.Success; Status = AllAssetObjects == null ? EStatus.Failed : EStatus.Succeed;
if (Status == EStatus.Fail) if (Status == EStatus.Failed)
{ {
if (MainAssetInfo.AssetType == null) if (MainAssetInfo.AssetType == null)
LastError = $"Failed to load sub assets : {MainAssetInfo.AssetPath} AssetType : null"; LastError = $"Failed to load sub assets : {MainAssetInfo.AssetPath} AssetType : null";

View File

@@ -13,8 +13,8 @@ namespace YooAsset
CheckBundle, CheckBundle,
Loading, Loading,
Checking, Checking,
Success, Succeed,
Fail, Failed,
} }
/// <summary> /// <summary>
@@ -47,6 +47,11 @@ namespace YooAsset
/// </summary> /// </summary>
public UnityEngine.SceneManagement.Scene SceneObject { protected set; get; } public UnityEngine.SceneManagement.Scene SceneObject { protected set; get; }
/// <summary>
/// 原生文件路径
/// </summary>
public string RawFilePath { protected set; get; }
/// <summary> /// <summary>
/// 当前的加载状态 /// 当前的加载状态
@@ -58,6 +63,11 @@ namespace YooAsset
/// </summary> /// </summary>
public string LastError { protected set; get; } = string.Empty; public string LastError { protected set; get; } = string.Empty;
/// <summary>
/// 加载进度
/// </summary>
public float Progress { protected set; get; } = 0f;
/// <summary> /// <summary>
/// 引用计数 /// 引用计数
/// </summary> /// </summary>
@@ -75,18 +85,7 @@ namespace YooAsset
{ {
get get
{ {
return Status == EStatus.Success || Status == EStatus.Fail; return Status == EStatus.Succeed || Status == EStatus.Failed;
}
}
/// <summary>
/// 加载进度
/// </summary>
public virtual float Progress
{
get
{
return 0;
} }
} }
@@ -115,6 +114,14 @@ namespace YooAsset
IsDestroyed = true; IsDestroyed = true;
} }
/// <summary>
/// 获取下载进度
/// </summary>
public virtual DownloadReport GetDownloadReport()
{
return DownloadReport.CreateDefaultReport();
}
/// <summary> /// <summary>
/// 是否可以销毁 /// 是否可以销毁
/// </summary> /// </summary>
@@ -152,6 +159,8 @@ namespace YooAsset
handle = new SceneOperationHandle(this); handle = new SceneOperationHandle(this);
else if (typeof(T) == typeof(SubAssetsOperationHandle)) else if (typeof(T) == typeof(SubAssetsOperationHandle))
handle = new SubAssetsOperationHandle(this); handle = new SubAssetsOperationHandle(this);
else if (typeof(T) == typeof(RawFileOperationHandle))
handle = new RawFileOperationHandle(this);
else else
throw new System.NotImplementedException(); throw new System.NotImplementedException();
@@ -212,11 +221,14 @@ namespace YooAsset
private TaskCompletionSource<object> _taskCompletionSource; private TaskCompletionSource<object> _taskCompletionSource;
protected void InvokeCompletion() protected void InvokeCompletion()
{ {
// 进度百分百完成
Progress = 1f;
// 注意:创建临时列表是为了防止外部逻辑在回调函数内创建或者释放资源句柄。 // 注意:创建临时列表是为了防止外部逻辑在回调函数内创建或者释放资源句柄。
List<OperationHandleBase> tempers = new List<OperationHandleBase>(_handles); List<OperationHandleBase> tempers = new List<OperationHandleBase>(_handles);
foreach (var hande in tempers) foreach (var hande in tempers)
{ {
if (hande.IsValid) if (hande.IsValidWithWarning)
{ {
hande.InvokeCallback(); hande.InvokeCallback();
} }
@@ -238,6 +250,15 @@ namespace YooAsset
/// </summary> /// </summary>
public string SpawnTime = string.Empty; public string SpawnTime = string.Empty;
/// <summary>
/// 加载耗时(单位:毫秒)
/// </summary>
public long LoadingTime { protected set; get; }
// 加载耗时统计
private bool _isRecording = false;
private Stopwatch _watch;
[Conditional("DEBUG")] [Conditional("DEBUG")]
public void InitSpawnDebugInfo() public void InitSpawnDebugInfo()
{ {
@@ -251,6 +272,25 @@ namespace YooAsset
float s = UnityEngine.Mathf.FloorToInt(spawnTime - m * 60f - h * 3600f); float s = UnityEngine.Mathf.FloorToInt(spawnTime - m * 60f - h * 3600f);
return h.ToString("00") + ":" + m.ToString("00") + ":" + s.ToString("00"); return h.ToString("00") + ":" + m.ToString("00") + ":" + s.ToString("00");
} }
[Conditional("DEBUG")]
protected void DebugRecording()
{
if (_isRecording == false)
{
_isRecording = true;
_watch = Stopwatch.StartNew();
}
if (_watch != null)
{
if (IsDone)
{
LoadingTime = _watch.ElapsedMilliseconds;
_watch = null;
}
}
}
#endregion #endregion
} }
} }

View File

@@ -13,10 +13,8 @@ namespace YooAsset
private EOperationStatus _initializeStatus = EOperationStatus.None; private EOperationStatus _initializeStatus = EOperationStatus.None;
private EPlayMode _playMode; private EPlayMode _playMode;
private IBundleServices _bundleServices; private IBundleServices _bundleServices;
private IPlayModeServices _playModeServices;
private AssetSystemImpl _assetSystemImpl; private AssetSystemImpl _assetSystemImpl;
private EditorSimulateModeImpl _editorSimulateModeImpl;
private OfflinePlayModeImpl _offlinePlayModeImpl;
private HostPlayModeImpl _hostPlayModeImpl;
/// <summary> /// <summary>
/// 包裹名 /// 包裹名
@@ -59,11 +57,8 @@ namespace YooAsset
_isInitialize = false; _isInitialize = false;
_initializeError = string.Empty; _initializeError = string.Empty;
_initializeStatus = EOperationStatus.None; _initializeStatus = EOperationStatus.None;
_bundleServices = null; _bundleServices = null;
_editorSimulateModeImpl = null; _playModeServices = null;
_offlinePlayModeImpl = null;
_hostPlayModeImpl = null;
if (_assetSystemImpl != null) if (_assetSystemImpl != null)
{ {
@@ -78,6 +73,9 @@ namespace YooAsset
/// </summary> /// </summary>
public InitializationOperation InitializeAsync(InitializeParameters parameters) public InitializationOperation InitializeAsync(InitializeParameters parameters)
{ {
// 注意WebGL平台因为网络原因可能会初始化失败
ResetInitializeAfterFailed();
// 检测初始化参数合法性 // 检测初始化参数合法性
CheckInitializeParameters(parameters); CheckInitializeParameters(parameters);
@@ -86,35 +84,39 @@ namespace YooAsset
_assetSystemImpl = new AssetSystemImpl(); _assetSystemImpl = new AssetSystemImpl();
if (_playMode == EPlayMode.EditorSimulateMode) if (_playMode == EPlayMode.EditorSimulateMode)
{ {
_editorSimulateModeImpl = new EditorSimulateModeImpl(); var editorSimulateModeImpl = new EditorSimulateModeImpl();
_bundleServices = _editorSimulateModeImpl; _bundleServices = editorSimulateModeImpl;
_assetSystemImpl.Initialize(true, parameters.AssetLoadingMaxNumber, parameters.DecryptionServices, _bundleServices); _playModeServices = editorSimulateModeImpl;
_assetSystemImpl.Initialize(PackageName, true, parameters.AssetLoadingMaxNumber, parameters.DecryptionServices, _bundleServices);
var initializeParameters = parameters as EditorSimulateModeParameters; var initializeParameters = parameters as EditorSimulateModeParameters;
initializeOperation = _editorSimulateModeImpl.InitializeAsync( initializeOperation = editorSimulateModeImpl.InitializeAsync(initializeParameters.LocationToLower, initializeParameters.SimulatePatchManifestPath);
initializeParameters.LocationToLower,
initializeParameters.SimulatePatchManifestPath);
} }
else if (_playMode == EPlayMode.OfflinePlayMode) else if (_playMode == EPlayMode.OfflinePlayMode)
{ {
_offlinePlayModeImpl = new OfflinePlayModeImpl(); var offlinePlayModeImpl = new OfflinePlayModeImpl();
_bundleServices = _offlinePlayModeImpl; _bundleServices = offlinePlayModeImpl;
_assetSystemImpl.Initialize(false, parameters.AssetLoadingMaxNumber, parameters.DecryptionServices, _bundleServices); _playModeServices = offlinePlayModeImpl;
_assetSystemImpl.Initialize(PackageName, false, parameters.AssetLoadingMaxNumber, parameters.DecryptionServices, _bundleServices);
var initializeParameters = parameters as OfflinePlayModeParameters; var initializeParameters = parameters as OfflinePlayModeParameters;
initializeOperation = _offlinePlayModeImpl.InitializeAsync( initializeOperation = offlinePlayModeImpl.InitializeAsync(PackageName, initializeParameters.LocationToLower);
initializeParameters.LocationToLower,
PackageName);
} }
else if (_playMode == EPlayMode.HostPlayMode) else if (_playMode == EPlayMode.HostPlayMode)
{ {
_hostPlayModeImpl = new HostPlayModeImpl(); var hostPlayModeImpl = new HostPlayModeImpl();
_bundleServices = _hostPlayModeImpl; _bundleServices = hostPlayModeImpl;
_assetSystemImpl.Initialize(false, parameters.AssetLoadingMaxNumber, parameters.DecryptionServices, _bundleServices); _playModeServices = hostPlayModeImpl;
_assetSystemImpl.Initialize(PackageName, false, parameters.AssetLoadingMaxNumber, parameters.DecryptionServices, _bundleServices);
var initializeParameters = parameters as HostPlayModeParameters; var initializeParameters = parameters as HostPlayModeParameters;
initializeOperation = _hostPlayModeImpl.InitializeAsync( initializeOperation = hostPlayModeImpl.InitializeAsync(
PackageName,
initializeParameters.LocationToLower, initializeParameters.LocationToLower,
initializeParameters.DefaultHostServer, initializeParameters.DefaultHostServer,
initializeParameters.FallbackHostServer, initializeParameters.FallbackHostServer,
initializeParameters.QueryServices); initializeParameters.QueryServices
);
} }
else else
{ {
@@ -122,9 +124,22 @@ namespace YooAsset
} }
// 监听初始化结果 // 监听初始化结果
_isInitialize = true;
initializeOperation.Completed += InitializeOperation_Completed; initializeOperation.Completed += InitializeOperation_Completed;
return initializeOperation; return initializeOperation;
} }
private void ResetInitializeAfterFailed()
{
if (_isInitialize && _initializeStatus == EOperationStatus.Failed)
{
_isInitialize = false;
_initializeStatus = EOperationStatus.None;
_initializeError = string.Empty;
_bundleServices = null;
_playModeServices = null;
_assetSystemImpl = null;
}
}
private void CheckInitializeParameters(InitializeParameters parameters) private void CheckInitializeParameters(InitializeParameters parameters)
{ {
if (_isInitialize) if (_isInitialize)
@@ -180,117 +195,69 @@ namespace YooAsset
} }
/// <summary> /// <summary>
/// 向网络端请求静态资源版本 /// 向网络端请求最新的资源版本
/// </summary> /// </summary>
/// <param name="appendTimeTicks">在URL末尾添加时间戳</param>
/// <param name="timeout">超时时间默认值60秒</param> /// <param name="timeout">超时时间默认值60秒</param>
public UpdateStaticVersionOperation UpdateStaticVersionAsync(int timeout = 60) public UpdatePackageVersionOperation UpdatePackageVersionAsync(bool appendTimeTicks = true, int timeout = 60)
{ {
DebugCheckInitialize(); DebugCheckInitialize();
if (_playMode == EPlayMode.EditorSimulateMode) return _playModeServices.UpdatePackageVersionAsync(appendTimeTicks, timeout);
{
var operation = new EditorPlayModeUpdateStaticVersionOperation();
OperationSystem.StartOperation(operation);
return operation;
}
else if (_playMode == EPlayMode.OfflinePlayMode)
{
var operation = new OfflinePlayModeUpdateStaticVersionOperation();
OperationSystem.StartOperation(operation);
return operation;
}
else if (_playMode == EPlayMode.HostPlayMode)
{
return _hostPlayModeImpl.UpdateStaticVersionAsync(PackageName, timeout);
}
else
{
throw new NotImplementedException();
}
} }
/// <summary> /// <summary>
/// 向网络端请求并更新补丁清单 /// 向网络端请求并更新补丁清单
/// </summary> /// </summary>
/// <param name="packageCRC">更新的资源包裹版本</param> /// <param name="packageVersion">更新的包裹版本</param>
/// <param name="autoActiveManifest">自动激活清单</param>
/// <param name="timeout">超时时间默认值60秒</param> /// <param name="timeout">超时时间默认值60秒</param>
public UpdateManifestOperation UpdateManifestAsync(string packageCRC, int timeout = 60) public UpdatePackageManifestOperation UpdatePackageManifestAsync(string packageVersion, int timeout = 60)
{ {
DebugCheckInitialize(); DebugCheckInitialize();
DebugCheckUpdateManifest(); DebugCheckUpdateManifest();
if (_playMode == EPlayMode.EditorSimulateMode) return _playModeServices.UpdatePackageManifestAsync(packageVersion, timeout);
{
var operation = new EditorPlayModeUpdateManifestOperation();
OperationSystem.StartOperation(operation);
return operation;
}
else if (_playMode == EPlayMode.OfflinePlayMode)
{
var operation = new OfflinePlayModeUpdateManifestOperation();
OperationSystem.StartOperation(operation);
return operation;
}
else if (_playMode == EPlayMode.HostPlayMode)
{
return _hostPlayModeImpl.UpdatePatchManifestAsync(PackageName, packageCRC, timeout);
}
else
{
throw new NotImplementedException();
}
} }
/// <summary> /// <summary>
/// 弱联网情况下加载补丁清单 /// 预下载指定版本的包裹资源
/// 注意:当指定版本内容验证失败后会返回失败。
/// </summary> /// </summary>
/// <param name="packageCRC">指定的资源包裹版本</param> /// <param name="packageVersion">下载的包裹版本</param>
public UpdateManifestOperation WeaklyUpdateManifestAsync(string packageCRC) /// <param name="timeout">超时时间默认值60秒</param>
public PreDownloadPackageOperation PreDownloadPackageAsync(string packageVersion, int timeout = 60)
{ {
DebugCheckInitialize(); DebugCheckInitialize();
if (_playMode == EPlayMode.EditorSimulateMode) return _playModeServices.PreDownloadPackageAsync(packageVersion, timeout);
{
var operation = new EditorPlayModeUpdateManifestOperation();
OperationSystem.StartOperation(operation);
return operation;
}
else if (_playMode == EPlayMode.OfflinePlayMode)
{
var operation = new OfflinePlayModeUpdateManifestOperation();
OperationSystem.StartOperation(operation);
return operation;
}
else if (_playMode == EPlayMode.HostPlayMode)
{
return _hostPlayModeImpl.WeaklyUpdatePatchManifestAsync(PackageName, packageCRC);
}
else
{
throw new NotImplementedException();
}
} }
/// <summary> /// <summary>
/// 获取人类可读的版本信息 /// 检查包裹内容的完整性
/// </summary> /// </summary>
public string GetHumanReadableVersion() public CheckPackageContentsOperation CheckPackageContentsAsync(string packageVersion)
{ {
DebugCheckInitialize(); DebugCheckInitialize();
if (_playMode == EPlayMode.EditorSimulateMode) return _playModeServices.CheckPackageContentsOperation(packageVersion);
{ }
return _editorSimulateModeImpl.GetHumanReadableVersion();
} /// <summary>
else if (_playMode == EPlayMode.OfflinePlayMode) /// 清理包裹未使用的缓存文件
{ /// </summary>
return _offlinePlayModeImpl.GetHumanReadableVersion(); public ClearUnusedCacheFilesOperation ClearUnusedCacheFilesAsync()
} {
else if (_playMode == EPlayMode.HostPlayMode) DebugCheckInitialize();
{ var operation = new ClearUnusedCacheFilesOperation(this);
return _hostPlayModeImpl.GetHumanReadableVersion(); OperationSystem.StartOperation(operation);
} return operation;
else }
{
throw new NotImplementedException(); /// <summary>
} /// 获取本地包裹的版本信息
/// </summary>
public string GetPackageVersion()
{
DebugCheckInitialize();
if (_playModeServices.ActiveManifest == null)
return string.Empty;
return _playModeServices.ActiveManifest.PackageVersion;
} }
/// <summary> /// <summary>
@@ -298,11 +265,9 @@ namespace YooAsset
/// </summary> /// </summary>
public void UnloadUnusedAssets() public void UnloadUnusedAssets()
{ {
if (_isInitialize) DebugCheckInitialize();
{ _assetSystemImpl.Update();
_assetSystemImpl.Update(); _assetSystemImpl.UnloadUnusedAssets();
_assetSystemImpl.UnloadUnusedAssets();
}
} }
/// <summary> /// <summary>
@@ -310,10 +275,8 @@ namespace YooAsset
/// </summary> /// </summary>
public void ForceUnloadAllAssets() public void ForceUnloadAllAssets()
{ {
if (_isInitialize) DebugCheckInitialize();
{ _assetSystemImpl.ForceUnloadAllAssets();
_assetSystemImpl.ForceUnloadAllAssets();
}
} }
@@ -367,7 +330,7 @@ namespace YooAsset
{ {
DebugCheckInitialize(); DebugCheckInitialize();
string[] tags = new string[] { tag }; string[] tags = new string[] { tag };
return _bundleServices.GetAssetInfos(tags); return _playModeServices.ActiveManifest.GetAssetsInfoByTags(tags);
} }
/// <summary> /// <summary>
@@ -377,7 +340,7 @@ namespace YooAsset
public AssetInfo[] GetAssetInfos(string[] tags) public AssetInfo[] GetAssetInfos(string[] tags)
{ {
DebugCheckInitialize(); DebugCheckInitialize();
return _bundleServices.GetAssetInfos(tags); return _playModeServices.ActiveManifest.GetAssetsInfoByTags(tags);
} }
/// <summary> /// <summary>
@@ -398,81 +361,70 @@ namespace YooAsset
public bool CheckLocationValid(string location) public bool CheckLocationValid(string location)
{ {
DebugCheckInitialize(); DebugCheckInitialize();
string assetPath = _bundleServices.TryMappingToAssetPath(location); string assetPath = _playModeServices.ActiveManifest.TryMappingToAssetPath(location);
return string.IsNullOrEmpty(assetPath) == false; return string.IsNullOrEmpty(assetPath) == false;
} }
#endregion #endregion
#region #region
/// <summary> /// <summary>
/// 异步获取原生文件 /// 同步加载原生文件
/// </summary> /// </summary>
/// <param name="location">资源的定位地址</param> /// <param name="assetInfo">资源信息</param>
/// <param name="copyPath">拷贝路径</param> public RawFileOperationHandle LoadRawFileSync(AssetInfo assetInfo)
public RawFileOperation GetRawFileAsync(string location, string copyPath = null)
{ {
DebugCheckInitialize(); DebugCheckInitialize();
AssetInfo assetInfo = ConvertLocationToAssetInfo(location, null); return LoadRawFileInternal(assetInfo, true);
return GetRawFileInternal(assetInfo, copyPath);
} }
/// <summary> /// <summary>
/// 异步获取原生文件 /// 同步加载原生文件
/// </summary> /// </summary>
/// <param name="assetInfo">资源信息</param> /// <param name="location">资源的定位地址</param>
/// <param name="copyPath">拷贝路径</param> public RawFileOperationHandle LoadRawFileSync(string location)
public RawFileOperation GetRawFileAsync(AssetInfo assetInfo, string copyPath = null)
{ {
DebugCheckInitialize(); DebugCheckInitialize();
return GetRawFileInternal(assetInfo, copyPath); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, null);
return LoadRawFileInternal(assetInfo, true);
}
/// <summary>
/// 异步加载原生文件
/// </summary>
/// <param name="assetInfo">资源信息</param>
public RawFileOperationHandle LoadRawFileAsync(AssetInfo assetInfo)
{
DebugCheckInitialize();
return LoadRawFileInternal(assetInfo, false);
}
/// <summary>
/// 异步加载原生文件
/// </summary>
/// <param name="location">资源的定位地址</param>
public RawFileOperationHandle LoadRawFileAsync(string location)
{
DebugCheckInitialize();
AssetInfo assetInfo = ConvertLocationToAssetInfo(location, null);
return LoadRawFileInternal(assetInfo, false);
} }
private RawFileOperation GetRawFileInternal(AssetInfo assetInfo, string copyPath) private RawFileOperationHandle LoadRawFileInternal(AssetInfo assetInfo, bool waitForAsyncComplete)
{ {
if (assetInfo.IsInvalid)
{
YooLogger.Error($"Failed to get raw file. {assetInfo.Error}");
RawFileOperation operation = new CompletedRawFileOperation(assetInfo.Error, copyPath);
OperationSystem.StartOperation(operation);
return operation;
}
BundleInfo bundleInfo = _bundleServices.GetBundleInfo(assetInfo);
#if UNITY_EDITOR #if UNITY_EDITOR
if (bundleInfo.Bundle.IsRawFile == false) if (assetInfo.IsInvalid == false)
{ {
string error = $"Cannot load asset bundle file using {nameof(GetRawFileAsync)} method !"; BundleInfo bundleInfo = _bundleServices.GetBundleInfo(assetInfo);
YooLogger.Error(error); if (bundleInfo.Bundle.IsRawFile == false)
RawFileOperation operation = new CompletedRawFileOperation(error, copyPath); throw new Exception($"Cannot load asset bundle file using {nameof(LoadRawFileAsync)} method !");
OperationSystem.StartOperation(operation);
return operation;
} }
#endif #endif
if (_playMode == EPlayMode.EditorSimulateMode) var handle = _assetSystemImpl.LoadRawFileAsync(assetInfo);
{ if (waitForAsyncComplete)
RawFileOperation operation = new EditorPlayModeRawFileOperation(bundleInfo, copyPath); handle.WaitForAsyncComplete();
OperationSystem.StartOperation(operation); return handle;
return operation;
}
else if (_playMode == EPlayMode.OfflinePlayMode)
{
RawFileOperation operation = new OfflinePlayModeRawFileOperation(bundleInfo, copyPath);
OperationSystem.StartOperation(operation);
return operation;
}
else if (_playMode == EPlayMode.HostPlayMode)
{
RawFileOperation operation = new HostPlayModeRawFileOperation(bundleInfo, copyPath);
OperationSystem.StartOperation(operation);
return operation;
}
else
{
throw new NotImplementedException();
}
} }
#endregion #endregion
@@ -585,13 +537,7 @@ namespace YooAsset
{ {
BundleInfo bundleInfo = _bundleServices.GetBundleInfo(assetInfo); BundleInfo bundleInfo = _bundleServices.GetBundleInfo(assetInfo);
if (bundleInfo.Bundle.IsRawFile) if (bundleInfo.Bundle.IsRawFile)
{ throw new Exception($"Cannot load raw file using {nameof(LoadAssetAsync)} method !");
string error = $"Cannot load raw file using LoadAsset method !";
YooLogger.Error(error);
CompletedProvider completedProvider = new CompletedProvider(assetInfo);
completedProvider.SetCompleted(error);
return completedProvider.CreateHandle<AssetOperationHandle>();
}
} }
#endif #endif
@@ -680,13 +626,7 @@ namespace YooAsset
{ {
BundleInfo bundleInfo = _bundleServices.GetBundleInfo(assetInfo); BundleInfo bundleInfo = _bundleServices.GetBundleInfo(assetInfo);
if (bundleInfo.Bundle.IsRawFile) if (bundleInfo.Bundle.IsRawFile)
{ throw new Exception($"Cannot load raw file using {nameof(LoadSubAssetsAsync)} method !");
string error = $"Cannot load raw file using LoadSubAssets method !";
YooLogger.Error(error);
CompletedProvider completedProvider = new CompletedProvider(assetInfo);
completedProvider.SetCompleted(error);
return completedProvider.CreateHandle<SubAssetsOperationHandle>();
}
} }
#endif #endif
@@ -708,7 +648,7 @@ namespace YooAsset
public PatchDownloaderOperation CreatePatchDownloader(string tag, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public PatchDownloaderOperation CreatePatchDownloader(string tag, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
DebugCheckInitialize(); DebugCheckInitialize();
return CreatePatchDownloader(new string[] { tag }, downloadingMaxNumber, failedTryAgain, timeout); return _playModeServices.CreatePatchDownloaderByTags(new string[] { tag }, downloadingMaxNumber, failedTryAgain, timeout);
} }
/// <summary> /// <summary>
@@ -721,20 +661,7 @@ namespace YooAsset
public PatchDownloaderOperation CreatePatchDownloader(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public PatchDownloaderOperation CreatePatchDownloader(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
DebugCheckInitialize(); DebugCheckInitialize();
if (_playMode == EPlayMode.EditorSimulateMode || _playMode == EPlayMode.OfflinePlayMode) return _playModeServices.CreatePatchDownloaderByTags(tags, downloadingMaxNumber, failedTryAgain, timeout);
{
List<BundleInfo> downloadList = new List<BundleInfo>();
var operation = new PatchDownloaderOperation(downloadList, downloadingMaxNumber, failedTryAgain, timeout);
return operation;
}
else if (_playMode == EPlayMode.HostPlayMode)
{
return _hostPlayModeImpl.CreatePatchDownloaderByTags(tags, downloadingMaxNumber, failedTryAgain, timeout);
}
else
{
throw new NotImplementedException();
}
} }
/// <summary> /// <summary>
@@ -746,53 +673,7 @@ namespace YooAsset
public PatchDownloaderOperation CreatePatchDownloader(int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public PatchDownloaderOperation CreatePatchDownloader(int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
DebugCheckInitialize(); DebugCheckInitialize();
if (_playMode == EPlayMode.EditorSimulateMode || _playMode == EPlayMode.OfflinePlayMode) return _playModeServices.CreatePatchDownloaderByAll(downloadingMaxNumber, failedTryAgain, timeout);
{
List<BundleInfo> downloadList = new List<BundleInfo>();
var operation = new PatchDownloaderOperation(downloadList, downloadingMaxNumber, failedTryAgain, timeout);
return operation;
}
else if (_playMode == EPlayMode.HostPlayMode)
{
return _hostPlayModeImpl.CreatePatchDownloaderByAll(downloadingMaxNumber, failedTryAgain, timeout);
}
else
{
throw new NotImplementedException();
}
}
/// <summary>
/// 创建补丁下载器,用于下载更新指定的资源列表依赖的资源包文件
/// </summary>
/// <param name="locations">资源定位列表</param>
/// <param name="downloadingMaxNumber">同时下载的最大文件数</param>
/// <param name="failedTryAgain">下载失败的重试次数</param>
/// <param name="timeout">超时时间</param>
public PatchDownloaderOperation CreateBundleDownloader(string[] locations, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{
DebugCheckInitialize();
if (_playMode == EPlayMode.EditorSimulateMode || _playMode == EPlayMode.OfflinePlayMode)
{
List<BundleInfo> downloadList = new List<BundleInfo>();
var operation = new PatchDownloaderOperation(downloadList, downloadingMaxNumber, failedTryAgain, timeout);
return operation;
}
else if (_playMode == EPlayMode.HostPlayMode)
{
List<AssetInfo> assetInfos = new List<AssetInfo>(locations.Length);
foreach (var location in locations)
{
AssetInfo assetInfo = ConvertLocationToAssetInfo(location, null);
assetInfos.Add(assetInfo);
}
return _hostPlayModeImpl.CreatePatchDownloaderByPaths(assetInfos.ToArray(), downloadingMaxNumber, failedTryAgain, timeout);
}
else
{
throw new NotImplementedException();
}
} }
/// <summary> /// <summary>
@@ -805,20 +686,7 @@ namespace YooAsset
public PatchDownloaderOperation CreateBundleDownloader(AssetInfo[] assetInfos, int downloadingMaxNumber, int failedTryAgain, int timeout = 60) public PatchDownloaderOperation CreateBundleDownloader(AssetInfo[] assetInfos, int downloadingMaxNumber, int failedTryAgain, int timeout = 60)
{ {
DebugCheckInitialize(); DebugCheckInitialize();
if (_playMode == EPlayMode.EditorSimulateMode || _playMode == EPlayMode.OfflinePlayMode) return _playModeServices.CreatePatchDownloaderByPaths(assetInfos, downloadingMaxNumber, failedTryAgain, timeout);
{
List<BundleInfo> downloadList = new List<BundleInfo>();
var operation = new PatchDownloaderOperation(downloadList, downloadingMaxNumber, failedTryAgain, timeout);
return operation;
}
else if (_playMode == EPlayMode.HostPlayMode)
{
return _hostPlayModeImpl.CreatePatchDownloaderByPaths(assetInfos, downloadingMaxNumber, failedTryAgain, timeout);
}
else
{
throw new NotImplementedException();
}
} }
#endregion #endregion
@@ -832,7 +700,7 @@ namespace YooAsset
public PatchUnpackerOperation CreatePatchUnpacker(string tag, int unpackingMaxNumber, int failedTryAgain) public PatchUnpackerOperation CreatePatchUnpacker(string tag, int unpackingMaxNumber, int failedTryAgain)
{ {
DebugCheckInitialize(); DebugCheckInitialize();
return CreatePatchUnpacker(new string[] { tag }, unpackingMaxNumber, failedTryAgain); return _playModeServices.CreatePatchUnpackerByTags(new string[] { tag }, unpackingMaxNumber, failedTryAgain, int.MaxValue);
} }
/// <summary> /// <summary>
@@ -844,26 +712,7 @@ namespace YooAsset
public PatchUnpackerOperation CreatePatchUnpacker(string[] tags, int unpackingMaxNumber, int failedTryAgain) public PatchUnpackerOperation CreatePatchUnpacker(string[] tags, int unpackingMaxNumber, int failedTryAgain)
{ {
DebugCheckInitialize(); DebugCheckInitialize();
if (_playMode == EPlayMode.EditorSimulateMode) return _playModeServices.CreatePatchUnpackerByTags(tags, unpackingMaxNumber, failedTryAgain, int.MaxValue);
{
List<BundleInfo> downloadList = new List<BundleInfo>();
var operation = new PatchUnpackerOperation(downloadList, unpackingMaxNumber, failedTryAgain, int.MaxValue);
return operation;
}
else if (_playMode == EPlayMode.OfflinePlayMode)
{
List<BundleInfo> downloadList = new List<BundleInfo>();
var operation = new PatchUnpackerOperation(downloadList, unpackingMaxNumber, failedTryAgain, int.MaxValue);
return operation;
}
else if (_playMode == EPlayMode.HostPlayMode)
{
return _hostPlayModeImpl.CreatePatchUnpackerByTags(tags, unpackingMaxNumber, failedTryAgain, int.MaxValue);
}
else
{
throw new NotImplementedException();
}
} }
/// <summary> /// <summary>
@@ -874,58 +723,7 @@ namespace YooAsset
public PatchUnpackerOperation CreatePatchUnpacker(int unpackingMaxNumber, int failedTryAgain) public PatchUnpackerOperation CreatePatchUnpacker(int unpackingMaxNumber, int failedTryAgain)
{ {
DebugCheckInitialize(); DebugCheckInitialize();
if (_playMode == EPlayMode.EditorSimulateMode) return _playModeServices.CreatePatchUnpackerByAll(unpackingMaxNumber, failedTryAgain, int.MaxValue);
{
List<BundleInfo> downloadList = new List<BundleInfo>();
var operation = new PatchUnpackerOperation(downloadList, unpackingMaxNumber, failedTryAgain, int.MaxValue);
return operation;
}
else if (_playMode == EPlayMode.OfflinePlayMode)
{
List<BundleInfo> downloadList = new List<BundleInfo>();
var operation = new PatchUnpackerOperation(downloadList, unpackingMaxNumber, failedTryAgain, int.MaxValue);
return operation;
}
else if (_playMode == EPlayMode.HostPlayMode)
{
return _hostPlayModeImpl.CreatePatchUnpackerByAll(unpackingMaxNumber, failedTryAgain, int.MaxValue);
}
else
{
throw new NotImplementedException();
}
}
#endregion
#region
/// <summary>
/// 创建资源包裹下载器,用于下载更新指定资源版本所有的资源包文件
/// </summary>
/// <param name="packageCRC">指定更新的资源包裹版本</param>
/// <param name="timeout">超时时间</param>
public UpdatePackageOperation UpdatePackageAsync(string packageCRC, int timeout = 60)
{
DebugCheckInitialize();
if (_playMode == EPlayMode.EditorSimulateMode)
{
var operation = new EditorPlayModeUpdatePackageOperation();
OperationSystem.StartOperation(operation);
return operation;
}
else if (_playMode == EPlayMode.OfflinePlayMode)
{
var operation = new OfflinePlayModeUpdatePackageOperation();
OperationSystem.StartOperation(operation);
return operation;
}
else if (_playMode == EPlayMode.HostPlayMode)
{
return _hostPlayModeImpl.UpdatePackageAsync(PackageName, packageCRC, timeout);
}
else
{
throw new NotImplementedException();
}
} }
#endregion #endregion
@@ -938,7 +736,15 @@ namespace YooAsset
// NOTE : 编辑器模拟模式下始终返回TRUE // NOTE : 编辑器模拟模式下始终返回TRUE
if (_playMode == EPlayMode.EditorSimulateMode) if (_playMode == EPlayMode.EditorSimulateMode)
return true; return true;
return _bundleServices.IsIncludeBundleFile(fileName); return _playModeServices.ActiveManifest.IsIncludeBundleFile(fileName);
}
/// <summary>
/// 资源定位地址转换为资源信息类
/// </summary>
private AssetInfo ConvertLocationToAssetInfo(string location, System.Type assetType)
{
return _playModeServices.ActiveManifest.ConvertLocationToAssetInfo(location, assetType);
} }
#endregion #endregion
@@ -947,27 +753,9 @@ namespace YooAsset
private void DebugCheckInitialize() private void DebugCheckInitialize()
{ {
if (_initializeStatus == EOperationStatus.None) if (_initializeStatus == EOperationStatus.None)
throw new Exception("YooAssets initialize not completed !"); throw new Exception("Package initialize not completed !");
else if (_initializeStatus == EOperationStatus.Failed) else if (_initializeStatus == EOperationStatus.Failed)
throw new Exception($"YooAssets initialize failed : {_initializeError}"); throw new Exception($"Package initialize failed ! {_initializeError}");
}
[Conditional("DEBUG")]
private void DebugCheckLocation(string location)
{
if (string.IsNullOrEmpty(location) == false)
{
// 检查路径末尾是否有空格
int index = location.LastIndexOf(" ");
if (index != -1)
{
if (location.Length == index + 1)
YooLogger.Warning($"Found blank character in location : \"{location}\"");
}
if (location.IndexOfAny(System.IO.Path.GetInvalidPathChars()) >= 0)
YooLogger.Warning($"Found illegal character in location : \"{location}\"");
}
} }
[Conditional("DEBUG")] [Conditional("DEBUG")]
@@ -982,37 +770,12 @@ namespace YooAsset
#endregion #endregion
#region #region
internal List<DebugProviderInfo> GetDebugReportInfos() internal DebugPackageData GetDebugPackageData()
{ {
return _assetSystemImpl.GetDebugReportInfos(); DebugPackageData data = new DebugPackageData();
} data.PackageName = PackageName;
#endregion data.ProviderInfos = _assetSystemImpl.GetDebugReportInfos();
return data;
#region
/// <summary>
/// 资源定位地址转换为资源信息类,失败时内部会发出错误日志。
/// </summary>
/// <returns>如果转换失败会返回一个无效的资源信息类</returns>
private AssetInfo ConvertLocationToAssetInfo(string location, System.Type assetType)
{
DebugCheckLocation(location);
string assetPath = _bundleServices.MappingToAssetPath(location);
PatchAsset patchAsset = _bundleServices.TryGetPatchAsset(assetPath);
if (patchAsset != null)
{
AssetInfo assetInfo = new AssetInfo(patchAsset, assetType);
return assetInfo;
}
else
{
string error;
if (string.IsNullOrEmpty(location))
error = $"The location is null or empty !";
else
error = $"The location is invalid : {location}";
AssetInfo assetInfo = new AssetInfo(error);
return assetInfo;
}
} }
#endregion #endregion
} }

View File

@@ -2,7 +2,6 @@
using System.IO; using System.IO;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using UnityEngine;
namespace YooAsset namespace YooAsset
{ {
@@ -30,8 +29,8 @@ namespace YooAsset
/// </summary> /// </summary>
public static bool IsCached(PatchBundle patchBundle) public static bool IsCached(PatchBundle patchBundle)
{ {
string fileHash = patchBundle.FileHash; string cacheKey = patchBundle.CacheKey;
if (_cachedDic.ContainsKey(fileHash)) if (_cachedDic.ContainsKey(cacheKey))
{ {
string filePath = patchBundle.CachedFilePath; string filePath = patchBundle.CachedFilePath;
if (File.Exists(filePath)) if (File.Exists(filePath))
@@ -40,7 +39,7 @@ namespace YooAsset
} }
else else
{ {
_cachedDic.Remove(fileHash); _cachedDic.Remove(cacheKey);
YooLogger.Error($"Cache file is missing : {filePath}"); YooLogger.Error($"Cache file is missing : {filePath}");
return false; return false;
} }
@@ -56,12 +55,12 @@ namespace YooAsset
/// </summary> /// </summary>
public static void CacheBundle(PatchBundle patchBundle) public static void CacheBundle(PatchBundle patchBundle)
{ {
string fileHash = patchBundle.FileHash; string cacheKey = patchBundle.CacheKey;
if (_cachedDic.ContainsKey(fileHash) == false) if (_cachedDic.ContainsKey(cacheKey) == false)
{ {
string filePath = patchBundle.CachedFilePath; string filePath = patchBundle.CachedFilePath;
YooLogger.Log($"Cache verify file : {filePath}"); YooLogger.Log($"Cache verify file : {filePath}");
_cachedDic.Add(fileHash, patchBundle); _cachedDic.Add(cacheKey, patchBundle);
} }
} }
@@ -74,9 +73,9 @@ namespace YooAsset
} }
/// <summary> /// <summary>
/// 验证并缓存补丁包文件 /// 验证并缓存本地文件
/// </summary> /// </summary>
public static EVerifyResult VerifyAndCacheBundle(PatchBundle patchBundle, EVerifyLevel verifyLevel) public static EVerifyResult VerifyAndCacheLocalBundleFile(PatchBundle patchBundle, EVerifyLevel verifyLevel)
{ {
var verifyResult = VerifyContentInternal(patchBundle.CachedFilePath, patchBundle.FileSize, patchBundle.FileCRC, verifyLevel); var verifyResult = VerifyContentInternal(patchBundle.CachedFilePath, patchBundle.FileSize, patchBundle.FileCRC, verifyLevel);
if (verifyResult == EVerifyResult.Succeed) if (verifyResult == EVerifyResult.Succeed)
@@ -84,10 +83,40 @@ namespace YooAsset
return verifyResult; return verifyResult;
} }
/// <summary>
/// 验证并缓存下载文件
/// </summary>
public static EVerifyResult VerifyAndCacheDownloadBundleFile(string tempFilePath, PatchBundle patchBundle, EVerifyLevel verifyLevel)
{
var verifyResult = VerifyContentInternal(tempFilePath, patchBundle.FileSize, patchBundle.FileCRC, verifyLevel);
if (verifyResult == EVerifyResult.Succeed)
{
try
{
string destFilePath = patchBundle.CachedFilePath;
if (File.Exists(destFilePath))
File.Delete(destFilePath);
FileInfo fileInfo = new FileInfo(tempFilePath);
fileInfo.MoveTo(destFilePath);
}
catch (Exception)
{
verifyResult = EVerifyResult.FileMoveFailed;
}
if (verifyResult == EVerifyResult.Succeed)
{
CacheBundle(patchBundle);
}
}
return verifyResult;
}
/// <summary> /// <summary>
/// 验证文件完整性 /// 验证文件完整性
/// </summary> /// </summary>
public static EVerifyResult VerifyContentInternal(string filePath, long fileSize, string fileCRC, EVerifyLevel verifyLevel) private static EVerifyResult VerifyContentInternal(string filePath, long fileSize, string fileCRC, EVerifyLevel verifyLevel)
{ {
try try
{ {

View File

@@ -1,181 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
namespace YooAsset
{
/// <summary>
/// 本地缓存文件验证器
/// </summary>
internal abstract class CacheVerifier
{
public abstract void InitVerifier(List<VerifyInfo> verifyInfos);
public abstract bool UpdateVerifier();
public abstract float GetVerifierProgress();
public List<VerifyInfo> VerifySuccessList { protected set; get; }
public List<VerifyInfo> VerifyFailList { protected set; get; }
}
/// <summary>
/// 本地缓存文件验证器(线程版)
/// </summary>
internal class CacheVerifierWithThread : CacheVerifier
{
private readonly ThreadSyncContext _syncContext = new ThreadSyncContext();
private readonly List<VerifyInfo> _waitingList = new List<VerifyInfo>(1000);
private readonly List<VerifyInfo> _verifyingList = new List<VerifyInfo>(100);
private int _verifyMaxNum;
private int _verifyTotalCount;
public override void InitVerifier(List<VerifyInfo> verifyInfos)
{
_waitingList.AddRange(verifyInfos);
VerifySuccessList = new List<VerifyInfo>(verifyInfos.Count);
VerifyFailList = new List<VerifyInfo>(verifyInfos.Count);
// 设置同时验证的最大数
ThreadPool.GetMaxThreads(out int workerThreads, out int ioThreads);
YooLogger.Log($"Work threads : {workerThreads}, IO threads : {ioThreads}");
_verifyMaxNum = Math.Min(workerThreads, ioThreads);
_verifyTotalCount = _waitingList.Count;
if (_verifyMaxNum < 1)
_verifyMaxNum = 1;
}
public override bool UpdateVerifier()
{
_syncContext.Update();
if (_waitingList.Count == 0 && _verifyingList.Count == 0)
return true;
if (_verifyingList.Count >= _verifyMaxNum)
return false;
for (int i = _waitingList.Count - 1; i >= 0; i--)
{
if (_verifyingList.Count >= _verifyMaxNum)
break;
var verifyIno = _waitingList[i];
if (VerifyFileWithThread(verifyIno))
{
_waitingList.RemoveAt(i);
_verifyingList.Add(verifyIno);
}
else
{
YooLogger.Warning("The thread pool is failed queued.");
break;
}
}
return false;
}
public override float GetVerifierProgress()
{
if (_verifyTotalCount == 0)
return 1f;
return (float)(VerifySuccessList.Count + VerifyFailList.Count) / _verifyTotalCount;
}
private bool VerifyFileWithThread(VerifyInfo verifyInfo)
{
return ThreadPool.QueueUserWorkItem(new WaitCallback(VerifyInThread), verifyInfo);
}
private void VerifyInThread(object infoObj)
{
VerifyInfo verifyInfo = (VerifyInfo)infoObj;
verifyInfo.Result = CacheSystem.VerifyBundle(verifyInfo.VerifyBundle, CacheSystem.InitVerifyLevel);
_syncContext.Post(VerifyCallback, verifyInfo);
}
private void VerifyCallback(object obj)
{
VerifyInfo verifyIno = (VerifyInfo)obj;
if (verifyIno.Result == EVerifyResult.Succeed)
{
VerifySuccessList.Add(verifyIno);
CacheSystem.CacheBundle(verifyIno.VerifyBundle);
}
else
{
VerifyFailList.Add(verifyIno);
// NOTE不期望删除断点续传的资源文件
/*
if (File.Exists(patchBundle.CachedBundleFilePath))
File.Delete(patchBundle.CachedBundleFilePath);
*/
}
_verifyingList.Remove(verifyIno);
}
}
/// <summary>
/// 本地缓存文件验证器(非线程版)
/// </summary>
internal class CacheVerifierWithoutThread : CacheVerifier
{
private readonly List<VerifyInfo> _waitingList = new List<VerifyInfo>(1000);
private readonly List<VerifyInfo> _verifyingList = new List<VerifyInfo>(100);
private int _verifyMaxNum;
private int _verifyTotalCount;
public override void InitVerifier(List<VerifyInfo> verifyInfos)
{
_waitingList.AddRange(verifyInfos);
VerifySuccessList = new List<VerifyInfo>(verifyInfos.Count);
VerifyFailList = new List<VerifyInfo>(verifyInfos.Count);
// 设置同时验证的最大数
_verifyMaxNum = 32;
_verifyTotalCount = _waitingList.Count;
}
public override bool UpdateVerifier()
{
if (_waitingList.Count == 0 && _verifyingList.Count == 0)
return true;
for (int i = _waitingList.Count - 1; i >= 0; i--)
{
if (_verifyingList.Count >= _verifyMaxNum)
break;
var verifyIno = _waitingList[i];
VerifyFileWithoutThread(verifyIno);
_waitingList.RemoveAt(i);
_verifyingList.Add(verifyIno);
}
_verifyingList.Clear();
return false;
}
public override float GetVerifierProgress()
{
if (_verifyTotalCount == 0)
return 1f;
return (float)(VerifySuccessList.Count + VerifyFailList.Count) / _verifyTotalCount;
}
private void VerifyFileWithoutThread(VerifyInfo verifyIno)
{
var verifyResult = CacheSystem.VerifyAndCacheBundle(verifyIno.VerifyBundle, CacheSystem.InitVerifyLevel);
if (verifyResult == EVerifyResult.Succeed)
{
VerifySuccessList.Add(verifyIno);
}
else
{
VerifyFailList.Add(verifyIno);
// NOTE不期望删除断点续传的资源文件
/*
if (File.Exists(patchBundle.CachedBundleFilePath))
File.Delete(patchBundle.CachedBundleFilePath);
*/
}
}
}
}

View File

@@ -4,12 +4,17 @@ namespace YooAsset
/// <summary> /// <summary>
/// 下载文件校验结果 /// 下载文件校验结果
/// </summary> /// </summary>
public enum EVerifyResult internal enum EVerifyResult
{ {
/// <summary> /// <summary>
/// 文件不存在 /// 文件不存在
/// </summary> /// </summary>
FileNotExisted = -4, FileNotExisted = -5,
/// <summary>
/// 文件移动失败(重命名失败)
/// </summary>
FileMoveFailed = -4,
/// <summary> /// <summary>
/// 文件内容不足(小于正常大小) /// 文件内容不足(小于正常大小)

View File

@@ -1,10 +1,17 @@
using System; using System;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
[Serializable] [Serializable]
internal class DebugBundleInfo internal class DebugBundleInfo : IComparer<DebugBundleInfo>, IComparable<DebugBundleInfo>
{ {
/// <summary>
/// 包裹名
/// </summary>
public string PackageName { set; get; }
/// <summary> /// <summary>
/// 资源包名称 /// 资源包名称
/// </summary> /// </summary>
@@ -18,6 +25,15 @@ namespace YooAsset
/// <summary> /// <summary>
/// 加载状态 /// 加载状态
/// </summary> /// </summary>
public int Status; public string Status;
public int CompareTo(DebugBundleInfo other)
{
return Compare(this, other);
}
public int Compare(DebugBundleInfo a, DebugBundleInfo b)
{
return string.CompareOrdinal(a.BundleName, b.BundleName);
}
} }
} }

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