Compare commits

...

123 Commits

Author SHA1 Message Date
何冠峰
b1f02049cc Update CHANGELOG.md 2025-09-17 16:59:24 +08:00
何冠峰
512886cdf6 Update package.json 2025-09-17 16:58:59 +08:00
何冠峰
0c3ccc5c2f refactor: 适配引擎版本 2025-09-17 16:49:21 +08:00
何冠峰
b0ea03170f refactor : 移除下载器的timeout参数
可以使用看门狗机制代替。
2025-09-17 15:53:22 +08:00
何冠峰
2c3b890329 feat #642 2025-09-17 15:39:47 +08:00
何冠峰
0f39cb9444 update space shooter 2025-09-17 10:53:56 +08:00
何冠峰
8acc16d3f6 perf #632 2025-09-17 10:53:40 +08:00
何冠峰
fd1715a89b fix 修正无效警告 2025-09-17 10:51:24 +08:00
何冠峰
0934c813d1 fix #644 2025-09-13 18:18:31 +08:00
何冠峰
be71d38cd8 update AssetBundleBuilder 2025-09-11 19:20:16 +08:00
何冠峰
4cdfde31da update AssetArtScanner 2025-09-11 19:19:55 +08:00
何冠峰
0133549ef8 feat #638
修复问题,防止游离的Bundle加载任务出现。
2025-09-11 14:03:42 +08:00
何冠峰
81d9eb47c8 feat #638 2025-09-11 11:07:13 +08:00
何冠峰
5fde689f1f feat #640 2025-09-10 21:19:58 +08:00
何冠峰
5d51bfe751 feat #639
修复问题
2025-09-10 21:00:51 +08:00
何冠峰
ed86edd2b0 feat #639 2025-09-10 20:15:52 +08:00
何冠峰
f627b5b59a Update CHANGELOG.md 2025-09-10 12:05:31 +08:00
何冠峰
549ec74519 Update CHANGELOG.md 2025-09-09 20:06:53 +08:00
何冠峰
247ee31348 Update package.json 2025-09-09 20:06:31 +08:00
何冠峰
90d3a53bc3 fix #631 2025-09-09 19:06:17 +08:00
何冠峰
19f1d67a61 feat : 弱引用资源句柄 2025-09-09 18:31:02 +08:00
何冠峰
a71c46d1c4 feat : 构建过程图集依赖计算增加开关 2025-09-08 19:00:55 +08:00
何冠峰
82d7bc8fef fix #614 增加Taptap小游戏扩展类 2025-08-30 18:09:28 +08:00
何冠峰
cc85099253 update mini game
重构相关代码,使用通用逻辑
2025-08-30 17:38:26 +08:00
何冠峰
d392b02bd4 refactor : 重构了Web文件系统公共类
方便小游戏共用基础代码。
2025-08-30 17:30:29 +08:00
何冠峰
a5138b9846 feat : 在SBP构建管线里,自动建立主资源对象对图集的依赖关系 2025-08-29 19:06:55 +08:00
何冠峰
e1b6458c26 update space shooter 2025-08-29 19:04:29 +08:00
何冠峰
0f73dc3047 update sample 2025-08-28 22:08:02 +08:00
何冠峰
a85e49c22a fix #625 2025-08-28 22:07:00 +08:00
何冠峰
6b291de922 fix #617 2025-08-28 19:02:08 +08:00
何冠峰
a4b1300195 fix #623 2025-08-28 10:40:13 +08:00
何冠峰
6f34951a74 refactor #627 2025-08-28 10:27:37 +08:00
何冠峰
c798250258 feat : CRC工具类增加获取整形值的方法 2025-08-27 19:19:00 +08:00
何冠峰
6fc82bb55a feat : 新增配置参数控制缓存文件验证最大并发数 2025-08-27 18:03:53 +08:00
何冠峰
c22cf5ffeb fix #620 2025-08-27 16:04:18 +08:00
何冠峰
36bc24f9fd fix #622 2025-08-27 10:29:13 +08:00
何冠峰
addb0ecdfe build #621 2025-08-27 10:27:12 +08:00
何冠峰
89e23e0df8 perf : 优化异步操作系统的繁忙检测机制
默认情况下不必检测
2025-08-16 16:53:28 +08:00
何冠峰
e2f582834e fix #611 2025-08-13 10:29:41 +08:00
何冠峰
d2c2844f61 update mini game
移除冗余代码
2025-08-13 10:29:25 +08:00
何冠峰
1de64278ad sample : 新增生成内置清单文件的页面工具 2025-08-04 18:36:43 +08:00
何冠峰
227f2332a9 refactor : 重构内置文件的加载和拷贝逻辑。
优先使用File类拷贝文件
2025-08-04 17:26:57 +08:00
何冠峰
131614687c Update LICENSE 2025-07-30 14:18:26 +08:00
何冠峰
b8ec902f60 perf : IsUnpackBundleFile方法设置为虚方法 2025-07-29 14:34:59 +08:00
何冠峰
eb3e29b6ad style : 修改形参注释 2025-07-29 14:33:54 +08:00
何冠峰
11ed9d391a build : 预留构建Mono脚本资源包方法。 2025-07-25 16:09:29 +08:00
何冠峰
9cd50bc7f3 fix : 修复构建页面扩展类缺少指定属性报错的问题。 2025-07-25 15:43:37 +08:00
何冠峰
e92505ba88 samples : 增加自定义构建页面的扩展示例 2025-07-25 15:42:17 +08:00
何冠峰
06a670730c Update README.md 2025-07-25 14:50:13 +08:00
何冠峰
ccd21e56cb sample : 更新UniTask扩展库的说明文档 2025-07-24 16:35:22 +08:00
何冠峰
522bcc529a update UniTask sample 2025-07-24 14:56:58 +08:00
何冠峰
2254ac9f5e update UniTask sample
更新说明文档
2025-07-24 14:45:52 +08:00
何冠峰
956b3db71d Merge pull request #601 from GodChouyu/dev
UniTask示例删除UniTask源码,修改为扩展支持。
2025-07-24 11:31:33 +08:00
何冠峰
fb56959c61 style : 统一小游戏编码规范和命名规范 2025-07-24 11:21:37 +08:00
何冠峰
b9b9f4e37d feat : 新增支付宝小游戏文件系统扩展类 2025-07-24 11:18:29 +08:00
GodChouyu
c050d6d172 UniTask示例删除UniTask源码,修改为扩展支持。 2025-07-24 10:15:17 +08:00
何冠峰
baf76a454b Update CHANGELOG.md 2025-07-23 18:49:13 +08:00
何冠峰
385d343262 Update package.json 2025-07-23 18:49:02 +08:00
何冠峰
1f5ad24d44 test : 完善测试用例代码 2025-07-23 18:46:54 +08:00
何冠峰
fefc0043cf fix : 修正小游戏脚本编译错误 2025-07-23 18:46:12 +08:00
何冠峰
f49143d4f7 Update CHANGELOG.md 2025-07-23 17:12:19 +08:00
何冠峰
fd760b12a3 Update package.json 2025-07-23 17:12:05 +08:00
何冠峰
14cf8e9ca3 update space shooter 2025-07-23 17:11:49 +08:00
何冠峰
3595219a71 style : 移除冗余空格 2025-07-23 16:48:37 +08:00
何冠峰
a4c7d4b8f5 test : 修改资源清单加密解密测试用例 2025-07-23 15:41:57 +08:00
何冠峰
43c5c7fb53 feat : 增加构建前置处理扩展示例
内置清单构建
2025-07-23 15:41:00 +08:00
何冠峰
48d2b36d4e feat : 改进资源清单加密和解密接口 2025-07-23 15:38:29 +08:00
何冠峰
2fd87f4d4b test : 新增测试用例 2025-07-23 14:08:26 +08:00
何冠峰
0fd75b835a style : 修正参数命名 2025-07-23 14:07:12 +08:00
何冠峰
4489ca570b style : 修改日志 2025-07-23 14:06:32 +08:00
何冠峰
268792b576 fix #592
优化不必要的GC
2025-07-23 11:07:29 +08:00
何冠峰
33907ea967 fix #591
新增DISABLE_ONDEMAND_DOWNLOAD文件配置参数
2025-07-22 18:59:47 +08:00
何冠峰
5d7afff3e4 update mini game
增加单元测试用例
2025-07-22 17:40:39 +08:00
何冠峰
fa15f83d85 Update UnityWebCacheRequestOperation.cs 2025-07-22 17:36:39 +08:00
何冠峰
1801974c8a Update DownloadCenterOperation.cs 2025-07-22 10:11:22 +08:00
何冠峰
bfd476d59c Update DownloadCenterOperation.cs 2025-07-21 18:22:51 +08:00
何冠峰
7dd08e9634 update test sample 2025-07-21 18:05:08 +08:00
何冠峰
b2776b933a update mini game sample 2025-07-21 15:52:51 +08:00
何冠峰
9f09b6c526 update file system 2025-07-21 15:52:07 +08:00
何冠峰
01f6103b48 Update AssemblyInfo.cs 2025-07-21 15:48:52 +08:00
何冠峰
053b4a00d7 update test sample 2025-07-17 22:24:27 +08:00
何冠峰
db159428c6 update test sample
增加cache file system单元测试
2025-07-17 21:26:13 +08:00
何冠峰
ac7ee16017 update mini game 2025-07-17 21:23:34 +08:00
何冠峰
c2fb7c3cbb update package invoke
correct name
2025-07-17 21:09:35 +08:00
何冠峰
e70b0d37cd update extension sample 2025-07-17 21:00:46 +08:00
何冠峰
53db012fc8 update download system 2025-07-17 21:00:12 +08:00
何冠峰
b3622167da update download system
remove timeout
2025-07-17 20:59:15 +08:00
何冠峰
dd6fab46f9 update extension sample 2025-07-16 10:48:40 +08:00
何冠峰
f0796dccc9 Update GooglePlayFileSystem.cs 2025-07-10 22:50:43 +08:00
何冠峰
f383c59327 update mini game sample
新增Google Play文件系统扩展
2025-07-10 22:43:43 +08:00
何冠峰
e34b9270d2 update mini game
下载器相关代码重构
2025-07-10 10:58:44 +08:00
何冠峰
b90ab01fe9 update file system
下载器相关逻辑代码重构
2025-07-10 10:58:14 +08:00
何冠峰
236468b4a8 update download system
重构下载逻辑代码
2025-07-09 14:52:22 +08:00
何冠峰
6f5fcd55b1 style : 修正拼写错误 2025-07-08 16:42:21 +08:00
何冠峰
4b8f2e3acc update download system
重构下载逻辑代码
2025-07-08 16:41:50 +08:00
何冠峰
090e4f4b15 fix #590 2025-07-01 18:10:17 +08:00
何冠峰
53163a75ae Update CHANGELOG.md 2025-07-01 16:46:10 +08:00
何冠峰
273401cb20 Update package.json 2025-07-01 16:45:50 +08:00
何冠峰
97fe3b0681 update file system
修正2.3.11版本同步加载本地加密文件失败的问题。
2025-07-01 16:40:01 +08:00
何冠峰
d401086fd1 update test sample 2025-07-01 15:32:44 +08:00
何冠峰
e3a12ef361 style : file system code style 2025-07-01 11:06:41 +08:00
何冠峰
1b0288fcd0 update mini game
微信小游戏和抖音小游戏支持资源清单加密。
2025-06-30 16:19:59 +08:00
何冠峰
3ee94fb3b9 update extension sample 2025-06-30 15:43:47 +08:00
何冠峰
a0ea80c158 Update CHANGELOG.md 2025-06-30 12:06:30 +08:00
何冠峰
264415b362 Update package.json 2025-06-30 12:06:07 +08:00
何冠峰
6a76d44c38 update test sample 2025-06-30 11:30:56 +08:00
何冠峰
cebfd57851 update test sample 2025-06-30 11:22:38 +08:00
何冠峰
60eb1c3522 update test sample
修正单元测试失败
2025-06-30 11:07:46 +08:00
何冠峰
40c82835bf style : code style 2025-06-30 10:53:16 +08:00
何冠峰
a13913f572 Merge pull request #582 from hhmmLife/dev
fix: 只有递归收集依赖时,依赖列表中才默认包含主资源
2025-06-30 10:47:28 +08:00
何冠峰
150b46a0a7 update file system
新增ICopyLocalFileServices服务类
2025-06-27 17:42:57 +08:00
何冠峰
ebde5a52d3 fix #585 2025-06-25 19:27:52 +08:00
何冠峰
e57466e9e2 style : file system code 2025-06-25 18:12:37 +08:00
何冠峰
6f7fca7b34 perf : main thread sleep one 2025-06-25 18:10:50 +08:00
何冠峰
756331fe0b style : file system code 2025-06-25 18:04:53 +08:00
何冠峰
5139e2f3a7 update extension sample 2025-06-23 18:57:48 +08:00
hhmmLife
1c4aba6db5 fix: 只有递归收集依赖时,依赖列表中才默认包含主资源 2025-06-23 00:56:50 +08:00
何冠峰
44faa0c5e6 fix #572
修复了资源收集页面指定收集的预制体名称变动的问题。
2025-06-20 17:55:51 +08:00
何冠峰
72c97341b1 fix #579 2025-06-20 14:03:12 +08:00
何冠峰
9acc240b5a update extension sample 2025-06-20 11:36:56 +08:00
何冠峰
ed89e73d26 fix #576
资源清单加密和解密
2025-06-20 11:36:29 +08:00
何冠峰
9e33df0375 style :services code 2025-06-20 11:29:22 +08:00
何冠峰
6c98f9a09d update resource manager
新增初始化参数:WebGLForceSyncLoadAsset
2025-06-18 11:12:42 +08:00
761 changed files with 11387 additions and 76576 deletions

View File

@@ -2,6 +2,301 @@
All notable changes to this package will be documented in this file.
## [2.3.16] - 2025-09-17
### Improvements
- (#638) 优化了Provider加载机制引用计数为零时自动挂起
### Fixed
- (#644) [**严重**] 修复了2.3.15版本,资产量巨大的情况下,编辑器下模拟模式初始化耗时很久的问题。
### Added
- (#639) 新增了文件系统参数VIRTUAL_DOWNLOAD_MODE 和 VIRTUAL_DOWNLOAD_SPEED
编辑器下不需要构建AB也可以模拟远端资源下载等同真机运行环境。
```csharp
class DefaultEditorFIleSystem
{
/// <summary>
/// 模拟虚拟下载模式
/// </summary>
public bool VirtualDownloadMode { private set; get; } = false;
/// <summary>
/// 模拟虚拟下载的网速(单位:字节)
/// </summary>
public int VirtualDownloadSpeed { private set; get; } = 1024;
}
```
- (#640) 新增了文件系统参数VIRTUAL_WEBGL_MODE
编辑器下不需要构建AB也可以模拟小游戏开发环境等同真机运行环境。
```csharp
class DefaultEditorFIleSystem
{
/// <summary>
/// 模拟WebGL平台模式
/// </summary>
public bool VirtualWebGLMode { private set; get; } = false;
}
```
- (#642) 新增了文件系统参数DOWNLOAD_WATCH_DOG_TIME
监控时间范围内,如果没有接收到任何下载数据,那么直接终止任务!
```csharp
class DefaultCacheFIleSystem
{
/// <summary>
/// 自定义参数:下载任务的看门狗机制监控时间
/// </summary>
public int DownloadWatchDogTime { private set; get; } = int.MaxValue;
}
```
### Changed
- 下载器参数timeout移除。
可以使用文件系统的看门狗机制代替。
- (#632) IFilterRule接口变动。
收集器可以指定搜寻的资源类型,在收集目录资产量巨大的情况下,可以极大加快打包速度!
```csharp
public interface IFilterRule
{
/// <summary>
/// 搜寻的资源类型
/// 说明:使用引擎方法搜索获取所有资源列表
/// </summary>
string FindAssetType { get; }
}
```
## [2.3.15] - 2025-09-09
**重要**:升级了资源清单版本,不兼容老版本。建议重新提审安装包。
### Improvements
- 重构了UniTask扩展库的目录结构和说明文档。
- 重构了内置文件系统类的加载和拷贝逻辑,解决在一些特殊机型上遇到的偶发性拷贝失败问题。
- 增加了生成内置清单文件的窗口工具详情见扩展工程里CreateBuildinCatalog目录。
- 优化了异步操作系统的繁忙检测机制。
- (#621) 资源配置页面可以展示DependCollector和StaticCollector包含的文件列表内容。
- (#627) 优化了资源清单部分字段类型CRC字段从字符串类型调整为整形可以降低清单尺寸。
### Fixed
- 修复了构建页面扩展类缺少指定属性报错的问题。
- (#611) 修复了资源扫描器配置页面,修改备注信息后会丢失焦点的问题。
- (#622) 修复了纯鸿蒙系统读取内置加密文件失败的问题。
- (#620) 修复了LINUX系统URL地址转换失败的问题。
- (#631) 修复了NET 4.x程序集库Math.Clamp导致的编译错误。
### Added
- 新增了支持支付宝小游戏的文件系统扩展类。
- 新增了支持Taptap小游戏的文件系统扩展类。
- 新增了资源系统初始化参数UseWeakReferenceHandle
目前处于预览版可以在引擎设置页面开启宏YOOASSET_EXPERIMENTAL
```csharp
/// <summary>
/// 启用弱引用资源句柄
/// </summary>
public bool UseWeakReferenceHandle = false;
```
- 内置文件系统和缓存文件系统新增初始化参数FILE_VERIFY_MAX_CONCURRENCY
```csharp
/// <summary>
/// 自定义参数:初始化的时候缓存文件校验最大并发数
/// </summary>
public int FileVerifyMaxConcurrency { private set; get; }
```
- (#623) 内置构建管线新增构建参数StripUnityVersion
```csharp
/// <summary>
/// 从文件头里剥离Unity版本信息
/// </summary>
public bool StripUnityVersion = false;
```
- 可编程构建管线新增构建参数TrackSpriteAtlasDependencies
```csharp
/// <summary>
/// 自动建立资源对象对图集的依赖关系
/// </summary>
public bool TrackSpriteAtlasDependencies = false;
```
- (#617) 新增资源收集配置参数SupportExtensionless
在不需要模糊加载模式的前提下,关闭此选项,可以降低运行时内存大小。
该选项默认开启!
```csharp
public class CollectCommand
{
/// <summary>
/// 支持无后缀名的资源定位地址
/// </summary>
public bool SupportExtensionless { set; get; }
}
```
- (#625) 异步操作系统类新增监听方法。
```csharp
class OperationSystem
{
/// <summary>
/// 监听任务开始
/// </summary>
public static void RegisterStartCallback(Action<string, AsyncOperationBase> callback);
/// <summary>
/// 监听任务结束
/// </summary>
public static void RegisterFinishCallback(Action<string, AsyncOperationBase> callback);
}
```
## [2.3.14] - 2025-07-23
**重要****所有下载相关的超时参数timeout已更新判定逻辑**
超时不再以‘指定时间内未接收到任何数据’为判定条件,而是以‘指定时间内未完成整个下载任务’为判定条件。
### Improvements
- 重构了核心代码的下载逻辑,解决了同步加载触发的下载任务没有完成的问题。
- 扩展工程里新增了PreprocessBuildCatalog类用于处理在构建应用程序前自动生成内置资源目录文件。
- (#592) 优化了资源清单逻辑里不必要产生的GC逻辑。
### Fixed
- (#590) 修复了TryUnloadUnusedAsset方法在依赖嵌套层数过深导致没有卸载的问题。
### Added
- 新增了支持Google Play的文件系统扩展示例。
- 新增了支持DefaultCacheFileSystem的单元测试用例。
- 新增了文件系统配置参数DISABLE_ONDEMAND_DOWNLOAD
```csharp
public class FileSystemParametersDefine
{
// 禁用边玩边下机制
public const string DISABLE_ONDEMAND_DOWNLOAD = "DISABLE_ONDEMAND_DOWNLO";
}
```
### Changed
- IManifestServices接口拆分为了IManifestProcessServices和IManifestRestoreServices
```csharp
public interface IManifestProcessServices
{
/// <summary>
/// 处理资源清单(压缩或加密)
/// </summary>
byte[] ProcessManifest(byte[] fileData);
}
public interface IManifestRestoreServices
{
/// <summary>
/// 还原资源清单(解压或解密)
/// </summary>
byte[] RestoreManifest(byte[] fileData);
}
```
## [2.3.12] - 2025-07-01
### Improvements
- 优化了同步接口导致的资源拷贝和资源验证性能开销高的现象。
- 微信小游戏和抖音小游戏支持资源清单加密。
### Fixed
- (#579) 修复了2.3.10版本资源包构建页面里CopyBuildinFileParam无法编辑问题。
- (#572) 修复了资源收集页面指定收集的预制体名称变动的问题。
- (#582) 修复了非递归收集依赖时,依赖列表中才包含主资源的问题。
### Added
- 新增初始化参数WebGLForceSyncLoadAsset
```csharp
public abstract class InitializeParameters
{
/// <summary>
/// WebGL平台强制同步加载资源对象
/// </summary>Add commentMore actions
public bool WebGLForceSyncLoadAsset = false;
}
```
- (#576) 新增了资源清单服务类IManifestServices
```csharp
/// <summary>
/// 资源清单文件处理服务接口
/// </summary>
public interface IManifestServices
{
/// <summary>
/// 处理资源清单(压缩和加密)
/// </summary>
byte[] ProcessManifest(byte[] fileData);
/// <summary>
/// 还原资源清单(解压和解密)
/// </summary>
byte[] RestoreManifest(byte[] fileData);
}
```
- (#585) 新增了本地文件拷贝服务类ICopyLocalFileServices
```csharp
/// <summary>
/// 本地文件拷贝服务类
/// </summary>
public interface ICopyLocalFileServices
{
void CopyFile(LocalFileInfo sourceFileInfo, string destFilePath);
}
```
## [2.3.10] - 2025-06-17
### Improvements

View File

@@ -46,7 +46,7 @@ namespace YooAsset.Editor
}
catch (Exception e)
{
return new ScannerResult(e.StackTrace);
return new ScannerResult(e.Message, e.StackTrace);
}
}

View File

@@ -294,6 +294,11 @@ namespace YooAsset.Editor
_scannerListView.itemsSource = filterItems;
_scannerListView.Rebuild();
}
if (_lastModifyScannerIndex >= 0 && _lastModifyScannerIndex < _scannerListView.itemsSource.Count)
{
_scannerListView.selectedIndex = _lastModifyScannerIndex;
}
}
private List<AssetArtScanner> FilterScanners()
{

View File

@@ -18,6 +18,11 @@ namespace YooAsset.Editor
/// </summary>
public string ErrorInfo { private set; get; }
/// <summary>
/// 错误堆栈
/// </summary>
public string ErrorStack { private set; get; }
/// <summary>
/// 是否成功
/// </summary>
@@ -33,9 +38,10 @@ namespace YooAsset.Editor
}
public ScannerResult(string error)
public ScannerResult(string error, string stack)
{
ErrorInfo = error;
ErrorStack = stack;
}
public ScannerResult(string filePath, ScanReport report)
{

View File

@@ -67,15 +67,39 @@ namespace YooAsset.Editor
EditorPrefs.SetString(key, buildinFileCopyParams);
}
// EncyptionClassName
public static string GetPackageEncyptionClassName(string packageName, string buildPipeline)
// EncyptionServicesClassName
public static string GetPackageEncyptionServicesClassName(string packageName, string buildPipeline)
{
string key = $"{Application.productName}_{packageName}_{buildPipeline}_EncyptionClassName";
return EditorPrefs.GetString(key, string.Empty);
string key = $"{Application.productName}_{packageName}_{buildPipeline}_EncyptionServicesClassName";
return EditorPrefs.GetString(key, $"{typeof(EncryptionNone).FullName}");
}
public static void SetPackageEncyptionClassName(string packageName, string buildPipeline, string encyptionClassName)
public static void SetPackageEncyptionServicesClassName(string packageName, string buildPipeline, string encyptionClassName)
{
string key = $"{Application.productName}_{packageName}_{buildPipeline}_EncyptionClassName";
string key = $"{Application.productName}_{packageName}_{buildPipeline}_EncyptionServicesClassName";
EditorPrefs.SetString(key, encyptionClassName);
}
// ManifestProcessServicesClassName
public static string GetPackageManifestProcessServicesClassName(string packageName, string buildPipeline)
{
string key = $"{Application.productName}_{packageName}_{buildPipeline}_ManifestProcessServicesClassName";
return EditorPrefs.GetString(key, $"{typeof(ManifestProcessNone).FullName}");
}
public static void SetPackageManifestProcessServicesClassName(string packageName, string buildPipeline, string encyptionClassName)
{
string key = $"{Application.productName}_{packageName}_{buildPipeline}_ManifestProcessServicesClassName";
EditorPrefs.SetString(key, encyptionClassName);
}
// ManifestRestoreServicesClassName
public static string GetPackageManifestRestoreServicesClassName(string packageName, string buildPipeline)
{
string key = $"{Application.productName}_{packageName}_{buildPipeline}_ManifestRestoreServicesClassName";
return EditorPrefs.GetString(key, $"{typeof(ManifestRestoreNone).FullName}");
}
public static void SetPackageManifestRestoreServicesClassName(string packageName, string buildPipeline, string encyptionClassName)
{
string key = $"{Application.productName}_{packageName}_{buildPipeline}_ManifestRestoreServicesClassName";
EditorPrefs.SetString(key, encyptionClassName);
}

View File

@@ -77,6 +77,12 @@ namespace YooAsset.Editor
foreach (var classType in viewerClassTypes)
{
var buildPipelineAttribute = EditorTools.GetAttribute<BuildPipelineAttribute>(classType);
if (buildPipelineAttribute == null)
{
Debug.LogWarning($"The class {classType.FullName} need attribute {nameof(BuildPipelineAttribute)}");
continue;
}
string pipelineName = buildPipelineAttribute.PipelineName;
if (_viewClassDic.ContainsKey(pipelineName))
{

View File

@@ -27,7 +27,7 @@ namespace YooAsset.Editor
/// <summary>
/// 文件哈希值
/// </summary>
public string PackageFileCRC { set; get; }
public uint PackageFileCRC { set; get; }
/// <summary>
/// 文件哈希值

View File

@@ -13,6 +13,11 @@ namespace YooAsset.Editor
/// </summary>
private readonly Dictionary<string, BuildBundleInfo> _bundleInfoDic = new Dictionary<string, BuildBundleInfo>(10000);
/// <summary>
/// 图集资源集合
/// </summary>
public readonly List<BuildAssetInfo> SpriteAtlasAssetList = new List<BuildAssetInfo>(10000);
/// <summary>
/// 未被依赖的资源列表
/// </summary>
@@ -60,6 +65,12 @@ namespace YooAsset.Editor
newBundleInfo.PackAsset(assetInfo);
_bundleInfoDic.Add(bundleName, newBundleInfo);
}
// 统计所有的精灵图集
if (assetInfo.AssetInfo.IsSpriteAtlas())
{
SpriteAtlasAssetList.Add(assetInfo);
}
}
/// <summary>

View File

@@ -98,6 +98,15 @@ namespace YooAsset.Editor
/// </summary>
public IEncryptionServices EncryptionServices;
/// <summary>
/// 资源清单加密服务类
/// </summary>
public IManifestProcessServices ManifestProcessServices;
/// <summary>
/// 资源清单解密服务类
/// </summary>
public IManifestRestoreServices ManifestRestoreServices;
private string _pipelineOutputDirectory = string.Empty;
private string _packageOutputDirectory = string.Empty;

View File

@@ -14,7 +14,8 @@ namespace YooAsset.Editor
{
string buildinRootDirectory = buildParametersContext.GetBuildinRootDirectory();
string buildPackageName = buildParametersContext.Parameters.PackageName;
DefaultBuildinFileSystemBuild.CreateBuildinCatalogFile(buildPackageName, buildinRootDirectory);
var manifestServices = buildParametersContext.Parameters.ManifestRestoreServices;
CatalogTools.CreateCatalogFile(manifestServices, buildPackageName, buildinRootDirectory);
// 刷新目录
AssetDatabase.Refresh();

View File

@@ -2,6 +2,7 @@
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
namespace YooAsset.Editor
{
@@ -32,6 +33,7 @@ namespace YooAsset.Editor
PackageManifest manifest = new PackageManifest();
manifest.FileVersion = ManifestDefine.FileVersion;
manifest.EnableAddressable = buildMapContext.Command.EnableAddressable;
manifest.SupportExtensionless = buildMapContext.Command.SupportExtensionless;
manifest.LocationToLower = buildMapContext.Command.LocationToLower;
manifest.IncludeAssetGUID = buildMapContext.Command.IncludeAssetGUID;
manifest.OutputNameStyle = (int)buildParameters.FileNameStyle;
@@ -58,7 +60,7 @@ namespace YooAsset.Editor
if (processBundleDepends)
ProcessBuiltinBundleDependency(context, manifest);
// 创建补丁清单文本文件
// 创建资源清单文本文件
{
string fileName = YooAssetSettingsData.GetManifestJsonFileName(buildParameters.PackageName, buildParameters.PackageVersion);
string filePath = $"{packageOutputDirectory}/{fileName}";
@@ -66,18 +68,18 @@ namespace YooAsset.Editor
BuildLogger.Log($"Create package manifest file: {filePath}");
}
// 创建补丁清单二进制文件
// 创建资源清单二进制文件
string packageHash;
string packagePath;
{
string fileName = YooAssetSettingsData.GetManifestBinaryFileName(buildParameters.PackageName, buildParameters.PackageVersion);
packagePath = $"{packageOutputDirectory}/{fileName}";
ManifestTools.SerializeToBinary(packagePath, manifest);
ManifestTools.SerializeToBinary(packagePath, manifest, buildParameters.ManifestProcessServices);
packageHash = HashUtility.FileCRC32(packagePath);
BuildLogger.Log($"Create package manifest file: {packagePath}");
}
// 创建补丁清单哈希文件
// 创建资源清单哈希文件
{
string fileName = YooAssetSettingsData.GetPackageHashFileName(buildParameters.PackageName, buildParameters.PackageVersion);
string filePath = $"{packageOutputDirectory}/{fileName}";
@@ -85,7 +87,7 @@ namespace YooAsset.Editor
BuildLogger.Log($"Create package manifest hash file: {filePath}");
}
// 创建补丁清单版本文件
// 创建资源清单版本文件
{
string fileName = YooAssetSettingsData.GetPackageVersionFileName(buildParameters.PackageName);
string filePath = $"{packageOutputDirectory}/{fileName}";
@@ -97,7 +99,7 @@ namespace YooAsset.Editor
{
ManifestContext manifestContext = new ManifestContext();
byte[] bytesData = FileUtility.ReadAllBytes(packagePath);
manifestContext.Manifest = ManifestTools.DeserializeFromBinary(bytesData);
manifestContext.Manifest = ManifestTools.DeserializeFromBinary(bytesData, buildParameters.ManifestRestoreServices);
context.SetContextObject(manifestContext);
}
}
@@ -300,18 +302,40 @@ namespace YooAsset.Editor
#region YOOASSET_LEGACY_DEPENDENCY
private void ProcessBuiltinBundleDependency(BuildContext context, PackageManifest manifest)
{
// 注意:初始化资源清单建立引用关系
ManifestTools.InitManifest(manifest);
// 注意:如果是可编程构建管线,需要补充内置资源包
// 注意:该步骤依赖前面的操作!
var buildResultContext = context.TryGetContextObject<TaskBuilding_SBP.BuildResultContext>();
if (buildResultContext != null)
{
// 注意:初始化资源清单建立引用关系
ManifestTools.InitManifest(manifest);
ProcessBuiltinBundleReference(context, manifest, buildResultContext.BuiltinShadersBundleName);
ProcessBuiltinBundleReference(context, manifest, buildResultContext.MonoScriptsBundleName);
ProcessBuiltinBundleReference(manifest, buildResultContext.BuiltinShadersBundleName);
ProcessBuiltinBundleReference(manifest, buildResultContext.MonoScriptsBundleName);
var buildParametersContext = context.TryGetContextObject<BuildParametersContext>();
var buildParameters = buildParametersContext.Parameters;
if (buildParameters is ScriptableBuildParameters scriptableBuildParameters)
{
if (scriptableBuildParameters.TrackSpriteAtlasDependencies)
{
// 注意:检测是否开启图集模式
// 说明:需要记录主资源对象对图集的依赖关系!
if (EditorSettings.spritePackerMode != SpritePackerMode.Disabled)
{
var buildMapContext = context.GetContextObject<BuildMapContext>();
foreach (var spriteAtlasAsset in buildMapContext.SpriteAtlasAssetList)
{
string spriteAtlasBundleName = spriteAtlasAsset.BundleName;
ProcessBuiltinBundleReference(manifest, spriteAtlasBundleName);
}
}
}
}
}
}
private void ProcessBuiltinBundleReference(BuildContext context, PackageManifest manifest, string builtinBundleName)
private void ProcessBuiltinBundleReference(PackageManifest manifest, string builtinBundleName)
{
if (string.IsNullOrEmpty(builtinBundleName))
return;

View File

@@ -32,6 +32,7 @@ namespace YooAsset.Editor
// 收集器配置
buildReport.Summary.UniqueBundleName = buildMapContext.Command.UniqueBundleName;
buildReport.Summary.EnableAddressable = buildMapContext.Command.EnableAddressable;
buildReport.Summary.SupportExtensionless = buildMapContext.Command.SupportExtensionless;
buildReport.Summary.LocationToLower = buildMapContext.Command.LocationToLower;
buildReport.Summary.IncludeAssetGUID = buildMapContext.Command.IncludeAssetGUID;
buildReport.Summary.AutoCollectShaders = buildMapContext.Command.AutoCollectShaders;
@@ -43,7 +44,10 @@ namespace YooAsset.Editor
buildReport.Summary.EnableSharePackRule = buildParameters.EnableSharePackRule;
buildReport.Summary.SingleReferencedPackAlone = buildParameters.SingleReferencedPackAlone;
buildReport.Summary.FileNameStyle = buildParameters.FileNameStyle;
buildReport.Summary.EncryptionClassName = buildParameters.EncryptionServices == null ? "null" : buildParameters.EncryptionServices.GetType().FullName;
buildReport.Summary.EncryptionServicesClassName = buildParameters.EncryptionServices == null ? "null" : buildParameters.EncryptionServices.GetType().FullName;
buildReport.Summary.ManifestProcessServicesClassName = buildParameters.ManifestProcessServices == null ? "null" : buildParameters.ManifestProcessServices.GetType().FullName;
buildReport.Summary.ManifestRestoreServicesClassName = buildParameters.ManifestRestoreServices == null ? "null" : buildParameters.ManifestRestoreServices.GetType().FullName;
if (buildParameters is BuiltinBuildParameters)
{
var builtinBuildParameters = buildParameters as BuiltinBuildParameters;

View File

@@ -63,7 +63,7 @@ namespace YooAsset.Editor
protected abstract string GetUnityHash(BuildBundleInfo bundleInfo, BuildContext context);
protected abstract uint GetUnityCRC(BuildBundleInfo bundleInfo, BuildContext context);
protected abstract string GetBundleFileHash(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext);
protected abstract string GetBundleFileCRC(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext);
protected abstract uint GetBundleFileCRC(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext);
protected abstract long GetBundleFileSize(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext);
}
}

View File

@@ -45,10 +45,10 @@ namespace YooAsset.Editor
string filePath = bundleInfo.PackageSourceFilePath;
return HashUtility.FileMD5(filePath);
}
protected override string GetBundleFileCRC(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext)
protected override uint GetBundleFileCRC(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext)
{
string filePath = bundleInfo.PackageSourceFilePath;
return HashUtility.FileCRC32(filePath);
return HashUtility.FileCRC32Value(filePath);
}
protected override long GetBundleFileSize(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext)
{

View File

@@ -12,6 +12,11 @@ namespace YooAsset.Editor
/// </summary>
public ECompressOption CompressOption = ECompressOption.Uncompressed;
/// <summary>
/// 从文件头里剥离Unity版本信息
/// </summary>
public bool StripUnityVersion = false;
/// <summary>
/// 禁止写入类型树结构(可以降低包体和内存并提高加载效率)
/// </summary>
@@ -41,6 +46,8 @@ namespace YooAsset.Editor
if (ClearBuildCacheFiles)
opt |= BuildAssetBundleOptions.ForceRebuildAssetBundle; //Force rebuild the asset bundles
if (StripUnityVersion)
opt |= BuildAssetBundleOptions.AssetBundleStripUnityVersion; //Removes the Unity Version number in the Archive File & Serialized File headers
if (DisableWriteTypeTree)
opt |= BuildAssetBundleOptions.DisableWriteTypeTree; //Do not include type information within the asset bundle (don't write type tree).
if (IgnoreTypeTreeChanges)

View File

@@ -24,9 +24,9 @@ namespace YooAsset.Editor
string filePath = bundleInfo.PackageSourceFilePath;
return GetFilePathTempHash(filePath);
}
protected override string GetBundleFileCRC(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext)
protected override uint GetBundleFileCRC(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext)
{
return "00000000"; //8位
return 0;
}
protected override long GetBundleFileSize(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext)
{

View File

@@ -27,10 +27,10 @@ namespace YooAsset.Editor
string filePath = bundleInfo.PackageSourceFilePath;
return HashUtility.FileMD5(filePath);
}
protected override string GetBundleFileCRC(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext)
protected override uint GetBundleFileCRC(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext)
{
string filePath = bundleInfo.PackageSourceFilePath;
return HashUtility.FileCRC32(filePath);
return HashUtility.FileCRC32Value(filePath);
}
protected override long GetBundleFileSize(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext)
{

View File

@@ -45,10 +45,10 @@ namespace YooAsset.Editor
string filePath = bundleInfo.PackageSourceFilePath;
return HashUtility.FileMD5(filePath);
}
protected override string GetBundleFileCRC(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext)
protected override uint GetBundleFileCRC(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext)
{
string filePath = bundleInfo.PackageSourceFilePath;
return HashUtility.FileCRC32(filePath);
return HashUtility.FileCRC32Value(filePath);
}
protected override long GetBundleFileSize(BuildBundleInfo bundleInfo, BuildParametersContext buildParametersContext)
{

View File

@@ -15,7 +15,7 @@ namespace YooAsset.Editor
public ECompressOption CompressOption = ECompressOption.Uncompressed;
/// <summary>
/// 从AssetBundle文件头里剥离Unity版本信息
/// 从文件头里剥离Unity版本信息
/// </summary>
public bool StripUnityVersion = false;
@@ -25,10 +25,15 @@ namespace YooAsset.Editor
public bool DisableWriteTypeTree = false;
/// <summary>
/// 忽略类型树变化
/// 忽略类型树变化(无效参数)
/// </summary>
public bool IgnoreTypeTreeChanges = true;
/// <summary>
/// 自动建立资源对象对图集的依赖关系
/// </summary>
public bool TrackSpriteAtlasDependencies = false;
/// <summary>
/// 生成代码防裁剪配置
@@ -76,10 +81,9 @@ namespace YooAsset.Editor
throw new System.NotImplementedException(CompressOption.ToString());
if (StripUnityVersion)
buildParams.ContentBuildFlags |= UnityEditor.Build.Content.ContentBuildFlags.StripUnityVersion;
buildParams.ContentBuildFlags |= UnityEditor.Build.Content.ContentBuildFlags.StripUnityVersion; // Build Flag to indicate the Unity Version should not be written to the serialized file.
if (DisableWriteTypeTree)
buildParams.ContentBuildFlags |= UnityEditor.Build.Content.ContentBuildFlags.DisableWriteTypeTree;
buildParams.ContentBuildFlags |= UnityEditor.Build.Content.ContentBuildFlags.DisableWriteTypeTree; //Do not include type information within the built content.
buildParams.UseCache = true;
buildParams.CacheServerHost = CacheServerHost;

View File

@@ -21,6 +21,11 @@ namespace YooAsset.Editor
/// </summary>
public string ErrorInfo;
/// <summary>
/// 构建失败的堆栈
/// </summary>
public string ErrorStack;
/// <summary>
/// 输出的补丁包目录
/// </summary>

View File

@@ -51,6 +51,7 @@ namespace YooAsset.Editor
EditorTools.ClearProgressBar();
buildResult.FailedTask = task.GetType().Name;
buildResult.ErrorInfo = e.ToString();
buildResult.ErrorStack = e.StackTrace;
buildResult.Success = false;
break;
}

View File

@@ -0,0 +1,19 @@

namespace YooAsset.Editor
{
public class ManifestProcessNone : IManifestProcessServices
{
byte[] IManifestProcessServices.ProcessManifest(byte[] fileData)
{
return fileData;
}
}
public class ManifestRestoreNone : IManifestRestoreServices
{
byte[] IManifestRestoreServices.RestoreManifest(byte[] fileData)
{
return fileData;
}
}
}

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 94254ab8e4496214884c11a891c131c6
guid: 446513b0ea9f5d445ade0cfb09c5073b
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@@ -44,19 +44,47 @@ namespace YooAsset.Editor
}
/// <summary>
/// 创建加密类实例
/// 创建资源包加密服务类实例
/// </summary>
protected IEncryptionServices CreateEncryptionInstance()
protected IEncryptionServices CreateEncryptionServicesInstance()
{
var encyptionClassName = AssetBundleBuilderSetting.GetPackageEncyptionClassName(PackageName, PipelineName);
var encryptionClassTypes = EditorTools.GetAssignableTypes(typeof(IEncryptionServices));
var classType = encryptionClassTypes.Find(x => x.FullName.Equals(encyptionClassName));
var className = AssetBundleBuilderSetting.GetPackageEncyptionServicesClassName(PackageName, PipelineName);
var classTypes = EditorTools.GetAssignableTypes(typeof(IEncryptionServices));
var classType = classTypes.Find(x => x.FullName.Equals(className));
if (classType != null)
return (IEncryptionServices)Activator.CreateInstance(classType);
else
return null;
}
/// <summary>
/// 创建资源清单加密服务类实例
/// </summary>
protected IManifestProcessServices CreateManifestProcessServicesInstance()
{
var className = AssetBundleBuilderSetting.GetPackageManifestProcessServicesClassName(PackageName, PipelineName);
var classTypes = EditorTools.GetAssignableTypes(typeof(IManifestProcessServices));
var classType = classTypes.Find(x => x.FullName.Equals(className));
if (classType != null)
return (IManifestProcessServices)Activator.CreateInstance(classType);
else
return null;
}
/// <summary>
/// 创建资源清单解密服务类实例
/// </summary>
protected IManifestRestoreServices CreateManifestRestoreServicesInstance()
{
var className = AssetBundleBuilderSetting.GetPackageManifestRestoreServicesClassName(PackageName, PipelineName);
var classTypes = EditorTools.GetAssignableTypes(typeof(IManifestRestoreServices));
var classType = classTypes.Find(x => x.FullName.Equals(className));
if (classType != null)
return (IManifestRestoreServices)Activator.CreateInstance(classType);
else
return null;
}
#region UI元素通用处理方法
protected void SetBuildOutputField(TextField textField)
{
@@ -111,11 +139,15 @@ namespace YooAsset.Editor
AssetBundleBuilderSetting.SetPackageBuildinFileCopyOption(PackageName, PipelineName, (EBuildinFileCopyOption)enumField.value);
// 设置内置资源标签显隐
bool tagsFiledVisible = buildinFileCopyOption == EBuildinFileCopyOption.ClearAndCopyByTags || buildinFileCopyOption == EBuildinFileCopyOption.OnlyCopyByTags;
tagField.visible = tagsFiledVisible;
SetCopyBuildinFileTagsVisible(tagField);
});
UIElementsTools.SetElementLabelMinWidth(enumField, LabelMinWidth);
}
protected void SetCopyBuildinFileTagsVisible(TextField tagField)
{
var option = AssetBundleBuilderSetting.GetPackageBuildinFileCopyOption(PackageName, PipelineName);
tagField.visible = option == EBuildinFileCopyOption.ClearAndCopyByTags || option == EBuildinFileCopyOption.OnlyCopyByTags;
}
protected void SetCopyBuildinFileTagsField(TextField textField)
{
// 首包文件拷贝参数
@@ -149,35 +181,97 @@ namespace YooAsset.Editor
});
UIElementsTools.SetElementLabelMinWidth(toggle, LabelMinWidth);
}
protected PopupField<Type> CreateEncryptionField(VisualElement container)
protected PopupField<Type> CreateEncryptionServicesField(VisualElement container)
{
// 加密方法
var encryptionClassTypes = EditorTools.GetAssignableTypes(typeof(IEncryptionServices));
if (encryptionClassTypes.Count > 0)
// 资源包加密服务类
var classTypes = EditorTools.GetAssignableTypes(typeof(IEncryptionServices));
if (classTypes.Count > 0)
{
var encyptionClassName = AssetBundleBuilderSetting.GetPackageEncyptionClassName(PackageName, PipelineName);
int defaultIndex = encryptionClassTypes.FindIndex(x => x.FullName.Equals(encyptionClassName));
var className = AssetBundleBuilderSetting.GetPackageEncyptionServicesClassName(PackageName, PipelineName);
int defaultIndex = classTypes.FindIndex(x => x.FullName.Equals(className));
if (defaultIndex < 0)
defaultIndex = 0;
var encryptionField = new PopupField<Type>(encryptionClassTypes, defaultIndex);
encryptionField.label = "Encryption";
encryptionField.style.width = StyleWidth;
encryptionField.RegisterValueChangedCallback(evt =>
var popupField = new PopupField<Type>(classTypes, defaultIndex);
popupField.label = "Encryption Services";
popupField.style.width = StyleWidth;
popupField.RegisterValueChangedCallback(evt =>
{
AssetBundleBuilderSetting.SetPackageEncyptionClassName(PackageName, PipelineName, encryptionField.value.FullName);
AssetBundleBuilderSetting.SetPackageEncyptionServicesClassName(PackageName, PipelineName, popupField.value.FullName);
});
container.Add(encryptionField);
UIElementsTools.SetElementLabelMinWidth(encryptionField, LabelMinWidth);
return encryptionField;
container.Add(popupField);
UIElementsTools.SetElementLabelMinWidth(popupField, LabelMinWidth);
return popupField;
}
else
{
var encryptionField = new PopupField<Type>();
encryptionField.label = "Encryption";
encryptionField.style.width = StyleWidth;
container.Add(encryptionField);
UIElementsTools.SetElementLabelMinWidth(encryptionField, LabelMinWidth);
return encryptionField;
var popupField = new PopupField<Type>();
popupField.label = "Encryption Services";
popupField.style.width = StyleWidth;
container.Add(popupField);
UIElementsTools.SetElementLabelMinWidth(popupField, LabelMinWidth);
return popupField;
}
}
protected PopupField<Type> CreateManifestProcessServicesField(VisualElement container)
{
// 资源清单加密服务类
var classTypes = EditorTools.GetAssignableTypes(typeof(IManifestProcessServices));
if (classTypes.Count > 0)
{
var className = AssetBundleBuilderSetting.GetPackageManifestProcessServicesClassName(PackageName, PipelineName);
int defaultIndex = classTypes.FindIndex(x => x.FullName.Equals(className));
if (defaultIndex < 0)
defaultIndex = 0;
var popupField = new PopupField<Type>(classTypes, defaultIndex);
popupField.label = "Manifest Process Services";
popupField.style.width = StyleWidth;
popupField.RegisterValueChangedCallback(evt =>
{
AssetBundleBuilderSetting.SetPackageManifestProcessServicesClassName(PackageName, PipelineName, popupField.value.FullName);
});
container.Add(popupField);
UIElementsTools.SetElementLabelMinWidth(popupField, LabelMinWidth);
return popupField;
}
else
{
var popupField = new PopupField<Type>();
popupField.label = "Manifest Process Services";
popupField.style.width = StyleWidth;
container.Add(popupField);
UIElementsTools.SetElementLabelMinWidth(popupField, LabelMinWidth);
return popupField;
}
}
protected PopupField<Type> CreateManifestRestoreServicesField(VisualElement container)
{
// 资源清单加密服务类
var classTypes = EditorTools.GetAssignableTypes(typeof(IManifestRestoreServices));
if (classTypes.Count > 0)
{
var className = AssetBundleBuilderSetting.GetPackageManifestRestoreServicesClassName(PackageName, PipelineName);
int defaultIndex = classTypes.FindIndex(x => x.FullName.Equals(className));
if (defaultIndex < 0)
defaultIndex = 0;
var popupField = new PopupField<Type>(classTypes, defaultIndex);
popupField.label = "Manifest Restore Services";
popupField.style.width = StyleWidth;
popupField.RegisterValueChangedCallback(evt =>
{
AssetBundleBuilderSetting.SetPackageManifestRestoreServicesClassName(PackageName, PipelineName, popupField.value.FullName);
});
container.Add(popupField);
UIElementsTools.SetElementLabelMinWidth(popupField, LabelMinWidth);
return popupField;
}
else
{
var popupField = new PopupField<Type>();
popupField.label = "Manifest Restore Services";
popupField.style.width = StyleWidth;
container.Add(popupField);
UIElementsTools.SetElementLabelMinWidth(popupField, LabelMinWidth);
return popupField;
}
}
#endregion

View File

@@ -16,7 +16,9 @@ namespace YooAsset.Editor
protected TemplateContainer Root;
protected TextField _buildOutputField;
protected TextField _buildVersionField;
protected PopupField<Type> _encryptionField;
protected PopupField<Type> _encryptionServicesField;
protected PopupField<Type> _manifestProcessServicesField;
protected PopupField<Type> _manifestRestoreServicesField;
protected EnumField _compressionField;
protected EnumField _outputNameStyleField;
protected EnumField _copyBuildinFileOptionField;
@@ -43,9 +45,11 @@ namespace YooAsset.Editor
_buildVersionField = Root.Q<TextField>("BuildVersion");
SetBuildVersionField(_buildVersionField);
// 加密方法
var encryptionContainer = Root.Q("EncryptionContainer");
_encryptionField = CreateEncryptionField(encryptionContainer);
// 服务类
var popupContainer = Root.Q("PopupContainer");
_encryptionServicesField = CreateEncryptionServicesField(popupContainer);
_manifestProcessServicesField = CreateManifestProcessServicesField(popupContainer);
_manifestRestoreServicesField = CreateManifestRestoreServicesField(popupContainer);
// 压缩方式选项
_compressionField = Root.Q<EnumField>("Compression");
@@ -58,6 +62,7 @@ namespace YooAsset.Editor
// 首包文件拷贝参数
_copyBuildinFileTagsField = Root.Q<TextField>("CopyBuildinFileParam");
SetCopyBuildinFileTagsField(_copyBuildinFileTagsField);
SetCopyBuildinFileTagsVisible(_copyBuildinFileTagsField);
// 首包文件拷贝选项
_copyBuildinFileOptionField = Root.Q<EnumField>("CopyBuildinFileOption");
@@ -116,7 +121,9 @@ namespace YooAsset.Editor
buildParameters.CompressOption = compressOption;
buildParameters.ClearBuildCacheFiles = clearBuildCache;
buildParameters.UseAssetDependencyDB = useAssetDependencyDB;
buildParameters.EncryptionServices = CreateEncryptionInstance();
buildParameters.EncryptionServices = CreateEncryptionServicesInstance();
buildParameters.ManifestProcessServices = CreateManifestProcessServicesInstance();
buildParameters.ManifestRestoreServices = CreateManifestRestoreServicesInstance();
BuiltinBuildPipeline pipeline = new BuiltinBuildPipeline();
var buildResult = pipeline.Run(buildParameters, true);

View File

@@ -4,7 +4,7 @@
<ui:TextField picking-mode="Ignore" label="Build Version" name="BuildVersion" />
<ui:Toggle label="Clear Build Cache" name="ClearBuildCache" />
<ui:Toggle label="Use Asset Depend DB" name="UseAssetDependency" />
<ui:VisualElement name="EncryptionContainer" style="height: 24px;" />
<ui:VisualElement name="PopupContainer" style="flex-grow: 1;" />
<uie:EnumField label="Compression" value="Center" name="Compression" />
<uie:EnumField label="File Name Style" value="Center" name="FileNameStyle" />
<uie:EnumField label="Copy Buildin File Option" value="Center" name="CopyBuildinFileOption" />

View File

@@ -74,7 +74,6 @@ namespace YooAsset.Editor
buildParameters.FileNameStyle = fileNameStyle;
buildParameters.BuildinFileCopyOption = buildinFileCopyOption;
buildParameters.BuildinFileCopyParams = buildinFileCopyParams;
buildParameters.EncryptionServices = CreateEncryptionInstance();
EditorSimulateBuildPipeline pipeline = new EditorSimulateBuildPipeline();
var buildResult = pipeline.Run(buildParameters, true);

View File

@@ -16,7 +16,9 @@ namespace YooAsset.Editor
protected TemplateContainer Root;
protected TextField _buildOutputField;
protected TextField _buildVersionField;
protected PopupField<Type> _encryptionField;
protected PopupField<Type> _encryptionServicesField;
protected PopupField<Type> _manifestProcessServicesField;
protected PopupField<Type> _manifestRestoreServicesField;
protected EnumField _outputNameStyleField;
protected EnumField _copyBuildinFileOptionField;
protected TextField _copyBuildinFileTagsField;
@@ -43,8 +45,10 @@ namespace YooAsset.Editor
SetBuildVersionField(_buildVersionField);
// 加密方法
var encryptionContainer = Root.Q("EncryptionContainer");
_encryptionField = CreateEncryptionField(encryptionContainer);
var popupContainer = Root.Q("PopupContainer");
_encryptionServicesField = CreateEncryptionServicesField(popupContainer);
_manifestProcessServicesField = CreateManifestProcessServicesField(popupContainer);
_manifestRestoreServicesField = CreateManifestRestoreServicesField(popupContainer);
// 输出文件名称样式
_outputNameStyleField = Root.Q<EnumField>("FileNameStyle");
@@ -53,6 +57,7 @@ namespace YooAsset.Editor
// 首包文件拷贝参数
_copyBuildinFileTagsField = Root.Q<TextField>("CopyBuildinFileParam");
SetCopyBuildinFileTagsField(_copyBuildinFileTagsField);
SetCopyBuildinFileTagsVisible(_copyBuildinFileTagsField);
// 首包文件拷贝选项
_copyBuildinFileOptionField = Root.Q<EnumField>("CopyBuildinFileOption");
@@ -108,7 +113,9 @@ namespace YooAsset.Editor
buildParameters.BuildinFileCopyParams = buildinFileCopyParams;
buildParameters.ClearBuildCacheFiles = clearBuildCache;
buildParameters.UseAssetDependencyDB = useAssetDependencyDB;
buildParameters.EncryptionServices = CreateEncryptionInstance();
buildParameters.EncryptionServices = CreateEncryptionServicesInstance();
buildParameters.ManifestProcessServices = CreateManifestProcessServicesInstance();
buildParameters.ManifestRestoreServices = CreateManifestRestoreServicesInstance();
RawFileBuildPipeline pipeline = new RawFileBuildPipeline();
var buildResult = pipeline.Run(buildParameters, true);

View File

@@ -4,7 +4,7 @@
<ui:TextField picking-mode="Ignore" label="Build Version" name="BuildVersion" />
<ui:Toggle label="Clear Build Cache" name="ClearBuildCache" />
<ui:Toggle label="Use Asset Depend DB" name="UseAssetDependency" />
<ui:VisualElement name="EncryptionContainer" style="height: 24px;" />
<ui:VisualElement name="PopupContainer" style="flex-grow: 1;" />
<uie:EnumField label="File Name Style" value="Center" name="FileNameStyle" />
<uie:EnumField label="Copy Buildin File Option" value="Center" name="CopyBuildinFileOption" />
<ui:TextField picking-mode="Ignore" label="Copy Buildin File Param" name="CopyBuildinFileParam" />

View File

@@ -16,7 +16,9 @@ namespace YooAsset.Editor
protected TemplateContainer Root;
protected TextField _buildOutputField;
protected TextField _buildVersionField;
protected PopupField<Type> _encryptionField;
protected PopupField<Type> _encryptionServicesField;
protected PopupField<Type> _manifestProcessServicesField;
protected PopupField<Type> _manifestRestoreServicesField;
protected EnumField _compressionField;
protected EnumField _outputNameStyleField;
protected EnumField _copyBuildinFileOptionField;
@@ -44,8 +46,10 @@ namespace YooAsset.Editor
SetBuildVersionField(_buildVersionField);
// 加密方法
var encryptionContainer = Root.Q("EncryptionContainer");
_encryptionField = CreateEncryptionField(encryptionContainer);
var popupContainer = Root.Q("PopupContainer");
_encryptionServicesField = CreateEncryptionServicesField(popupContainer);
_manifestProcessServicesField = CreateManifestProcessServicesField(popupContainer);
_manifestRestoreServicesField = CreateManifestRestoreServicesField(popupContainer);
// 压缩方式选项
_compressionField = Root.Q<EnumField>("Compression");
@@ -58,6 +62,7 @@ namespace YooAsset.Editor
// 首包文件拷贝参数
_copyBuildinFileTagsField = Root.Q<TextField>("CopyBuildinFileParam");
SetCopyBuildinFileTagsField(_copyBuildinFileTagsField);
SetCopyBuildinFileTagsVisible(_copyBuildinFileTagsField);
// 首包文件拷贝选项
_copyBuildinFileOptionField = Root.Q<EnumField>("CopyBuildinFileOption");
@@ -99,7 +104,6 @@ namespace YooAsset.Editor
var compressOption = AssetBundleBuilderSetting.GetPackageCompressOption(PackageName, PipelineName);
var clearBuildCache = AssetBundleBuilderSetting.GetPackageClearBuildCache(PackageName, PipelineName);
var useAssetDependencyDB = AssetBundleBuilderSetting.GetPackageUseAssetDependencyDB(PackageName, PipelineName);
var builtinShaderBundleName = GetBuiltinShaderBundleName();
ScriptableBuildParameters buildParameters = new ScriptableBuildParameters();
buildParameters.BuildOutputRoot = AssetBundleBuilderHelper.GetDefaultBuildOutputRoot();
@@ -117,8 +121,10 @@ namespace YooAsset.Editor
buildParameters.CompressOption = compressOption;
buildParameters.ClearBuildCacheFiles = clearBuildCache;
buildParameters.UseAssetDependencyDB = useAssetDependencyDB;
buildParameters.BuiltinShadersBundleName = builtinShaderBundleName;
buildParameters.EncryptionServices = CreateEncryptionInstance();
buildParameters.EncryptionServices = CreateEncryptionServicesInstance();
buildParameters.ManifestProcessServices = CreateManifestProcessServicesInstance();
buildParameters.ManifestRestoreServices = CreateManifestRestoreServicesInstance();
buildParameters.BuiltinShadersBundleName = GetBuiltinShaderBundleName();
ScriptableBuildPipeline pipeline = new ScriptableBuildPipeline();
var buildResult = pipeline.Run(buildParameters, true);
@@ -136,6 +142,16 @@ namespace YooAsset.Editor
var packRuleResult = DefaultPackRule.CreateShadersPackRuleResult();
return packRuleResult.GetBundleName(PackageName, uniqueBundleName);
}
/// <summary>
/// Mono脚本的资源包名称
/// </summary>
protected string GetMonoScriptsBundleName()
{
var uniqueBundleName = AssetBundleCollectorSettingData.Setting.UniqueBundleName;
var packRuleResult = DefaultPackRule.CreateMonosPackRuleResult();
return packRuleResult.GetBundleName(PackageName, uniqueBundleName);
}
}
}
#endif

View File

@@ -4,7 +4,7 @@
<ui:TextField picking-mode="Ignore" label="Build Version" name="BuildVersion" />
<ui:Toggle label="Clear Build Cache" name="ClearBuildCache" />
<ui:Toggle label="Use Asset Depend DB" name="UseAssetDependency" />
<ui:VisualElement name="EncryptionContainer" style="height: 24px;" />
<ui:VisualElement name="PopupContainer" style="flex-grow: 1;" />
<uie:EnumField label="Compression" value="Center" name="Compression" />
<uie:EnumField label="File Name Style" value="Center" name="FileNameStyle" />
<uie:EnumField label="Copy Buildin File Option" value="Center" name="CopyBuildinFileOption" />

View File

@@ -139,10 +139,17 @@ namespace YooAsset.Editor
/// </summary>
public List<CollectAssetInfo> GetAllCollectAssets(CollectCommand command, AssetBundleCollectorGroup group)
{
// 注意:模拟构建模式下只收集主资源
if (command.SimulateBuild)
bool ignoreStaticCollector = command.IsFlagSet(ECollectFlags.IgnoreStaticCollector);
if (ignoreStaticCollector)
{
if (CollectorType != ECollectorType.MainAssetCollector)
if (CollectorType == ECollectorType.StaticAssetCollector)
return new List<CollectAssetInfo>();
}
bool ignoreDependCollector = command.IsFlagSet(ECollectFlags.IgnoreDependCollector);
if (ignoreDependCollector)
{
if (CollectorType == ECollectorType.DependAssetCollector)
return new List<CollectAssetInfo>();
}
@@ -152,8 +159,10 @@ namespace YooAsset.Editor
List<string> findAssets = new List<string>();
if (AssetDatabase.IsValidFolder(CollectPath))
{
string collectDirectory = CollectPath;
string[] findResult = EditorTools.FindAssets(EAssetSearchType.All, collectDirectory);
IFilterRule filterRuleInstance = AssetBundleCollectorSettingData.GetFilterRuleInstance(FilterRuleName);
string findAssetType = filterRuleInstance.FindAssetType;
string searchFolder = CollectPath;
string[] findResult = EditorTools.FindAssets(findAssetType, searchFolder);
findAssets.AddRange(findResult);
}
else
@@ -269,8 +278,8 @@ namespace YooAsset.Editor
}
private List<AssetInfo> GetAllDependencies(CollectCommand command, string mainAssetPath)
{
// 注意:模拟构建模式下不需要收集依赖资源
if (command.SimulateBuild)
bool ignoreGetDependencies = command.IsFlagSet(ECollectFlags.IgnoreGetDependencies);
if (ignoreGetDependencies)
return new List<AssetInfo>();
string[] depends = command.AssetDependency.GetDependencies(mainAssetPath, true);

View File

@@ -10,7 +10,7 @@ namespace YooAsset.Editor
{
public class AssetBundleCollectorConfig
{
public const string ConfigVersion = "v2.1";
public const string ConfigVersion = "v2025.8.28";
public const string XmlVersion = "Version";
public const string XmlCommon = "Common";
@@ -23,6 +23,7 @@ namespace YooAsset.Editor
public const string XmlPackageName = "PackageName";
public const string XmlPackageDesc = "PackageDesc";
public const string XmlEnableAddressable = "AutoAddressable";
public const string XmlSupportExtensionless = "SupportExtensionless";
public const string XmlLocationToLower = "LocationToLower";
public const string XmlIncludeAssetGUID = "IncludeAssetGUID";
public const string XmlIgnoreRuleName = "IgnoreRuleName";
@@ -99,6 +100,7 @@ namespace YooAsset.Editor
package.PackageName = packageElement.GetAttribute(XmlPackageName);
package.PackageDesc = packageElement.GetAttribute(XmlPackageDesc);
package.EnableAddressable = packageElement.GetAttribute(XmlEnableAddressable) == "True" ? true : false;
package.SupportExtensionless = packageElement.GetAttribute(XmlSupportExtensionless) == "True" ? true : false;
package.LocationToLower = packageElement.GetAttribute(XmlLocationToLower) == "True" ? true : false;
package.IncludeAssetGUID = packageElement.GetAttribute(XmlIncludeAssetGUID) == "True" ? true : false;
package.IgnoreRuleName = packageElement.GetAttribute(XmlIgnoreRuleName);
@@ -211,6 +213,7 @@ namespace YooAsset.Editor
packageElement.SetAttribute(XmlPackageName, package.PackageName);
packageElement.SetAttribute(XmlPackageDesc, package.PackageDesc);
packageElement.SetAttribute(XmlEnableAddressable, package.EnableAddressable.ToString());
packageElement.SetAttribute(XmlSupportExtensionless, package.SupportExtensionless.ToString());
packageElement.SetAttribute(XmlLocationToLower, package.LocationToLower.ToString());
packageElement.SetAttribute(XmlIncludeAssetGUID, package.IncludeAssetGUID.ToString());
packageElement.SetAttribute(XmlIgnoreRuleName, package.IgnoreRuleName);
@@ -275,6 +278,23 @@ namespace YooAsset.Editor
return UpdateXmlConfig(xmlDoc);
}
// v2.1 -> v2025.8.28
if (configVersion == "v2.1")
{
// 读取包裹配置
var packageNodeList = root.GetElementsByTagName(XmlPackage);
foreach (var packageNode in packageNodeList)
{
XmlElement packageElement = packageNode as XmlElement;
if (packageElement.HasAttribute(XmlSupportExtensionless) == false)
packageElement.SetAttribute(XmlSupportExtensionless, "True");
}
// 更新版本
root.SetAttribute(XmlVersion, "v2025.8.28");
return UpdateXmlConfig(xmlDoc);
}
return false;
}
}

View File

@@ -25,6 +25,11 @@ namespace YooAsset.Editor
/// </summary>
public bool EnableAddressable = false;
/// <summary>
/// 支持无后缀名的资源定位地址
/// </summary>
public bool SupportExtensionless = true;
/// <summary>
/// 资源定位地址大小写不敏感
/// </summary>

View File

@@ -111,6 +111,7 @@ namespace YooAsset.Editor
command.UniqueBundleName = UniqueBundleName;
command.UseAssetDependencyDB = useAssetDependencyDB;
command.EnableAddressable = package.EnableAddressable;
command.SupportExtensionless = package.SupportExtensionless;
command.LocationToLower = package.LocationToLower;
command.IncludeAssetGUID = package.IncludeAssetGUID;
command.AutoCollectShaders = package.AutoCollectShaders;

View File

@@ -38,6 +38,7 @@ namespace YooAsset.Editor
private VisualElement _setting2Container;
private Toggle _enableAddressableToogle;
private Toggle _supportExtensionlessToogle;
private Toggle _locationToLowerToogle;
private Toggle _includeAssetGUIDToogle;
private Toggle _autoCollectShadersToogle;
@@ -131,6 +132,17 @@ namespace YooAsset.Editor
RefreshWindow();
}
});
_supportExtensionlessToogle = root.Q<Toggle>("SupportExtensionless");
_supportExtensionlessToogle.RegisterValueChangedCallback(evt =>
{
var selectPackage = _packageListView.selectedItem as AssetBundleCollectorPackage;
if (selectPackage != null)
{
selectPackage.SupportExtensionless = evt.newValue;
AssetBundleCollectorSettingData.ModifyPackage(selectPackage);
RefreshWindow();
}
});
_locationToLowerToogle = root.Q<Toggle>("LocationToLower");
_locationToLowerToogle.RegisterValueChangedCallback(evt =>
{
@@ -487,6 +499,7 @@ namespace YooAsset.Editor
_packageSettingsButton.SetEnabled(true);
_packageSettingsButton.text = $"{packageSettingName} ({selectPackage.PackageName})";
_enableAddressableToogle.SetValueWithoutNotify(selectPackage.EnableAddressable);
_supportExtensionlessToogle.SetValueWithoutNotify(selectPackage.SupportExtensionless);
_locationToLowerToogle.SetValueWithoutNotify(selectPackage.LocationToLower);
_includeAssetGUIDToogle.SetValueWithoutNotify(selectPackage.IncludeAssetGUID);
_autoCollectShadersToogle.SetValueWithoutNotify(selectPackage.AutoCollectShaders);
@@ -762,6 +775,7 @@ namespace YooAsset.Editor
elementTop.Add(objectField);
var label = objectField.Q<Label>();
label.style.minWidth = 63;
UIElementsTools.SetObjectFieldShowPath(objectField);
}
// Bottom VisualElement
@@ -830,7 +844,7 @@ namespace YooAsset.Editor
var foldout = new Foldout();
foldout.name = "Foldout1";
foldout.value = false;
foldout.text = "Main Assets";
foldout.text = "Assets";
elementFoldout.Add(foldout);
}
@@ -851,8 +865,6 @@ namespace YooAsset.Editor
var collector = selectGroup.Collectors[index];
var collectObject = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(collector.CollectPath);
if (collectObject != null)
collectObject.name = collector.CollectPath;
// 注意:非主资源收集器的标签栏需要被冻结
var textTags = element.Q<TextField>("TextField1");
@@ -865,11 +877,9 @@ namespace YooAsset.Editor
var foldout = element.Q<Foldout>("Foldout1");
foldout.RegisterValueChangedCallback(evt =>
{
if (evt.newValue)
RefreshFoldout(foldout, selectGroup, collector);
else
foldout.Clear();
RefreshFoldoutContent(foldout, selectGroup, collector);
});
RefreshFoldoutName(foldout, collector.CollectorType);
// Remove Button
var removeBtn = element.Q<Button>("Button1");
@@ -885,13 +895,10 @@ namespace YooAsset.Editor
{
collector.CollectPath = AssetDatabase.GetAssetPath(evt.newValue);
collector.CollectorGUID = AssetDatabase.AssetPathToGUID(collector.CollectPath);
objectField1.value.name = collector.CollectPath;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
RefreshFoldoutContent(foldout, selectGroup, collector);
});
UIElementsTools.RefreshObjectFieldShowPath(objectField1);
// Collector Type
var popupField0 = element.Q<PopupField<string>>("PopupField0");
@@ -900,10 +907,7 @@ namespace YooAsset.Editor
{
collector.CollectorType = EditorTools.NameToEnum<ECollectorType>(evt.newValue);
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
RefreshFoldoutContent(foldout, selectGroup, collector);
if (collector.CollectorType == ECollectorType.MainAssetCollector)
textTags.SetEnabled(true);
@@ -922,10 +926,7 @@ namespace YooAsset.Editor
{
collector.AddressRuleName = evt.newValue.ClassName;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
RefreshFoldoutContent(foldout, selectGroup, collector);
});
}
@@ -938,10 +939,7 @@ namespace YooAsset.Editor
{
collector.PackRuleName = evt.newValue.ClassName;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
RefreshFoldoutContent(foldout, selectGroup, collector);
});
// Filter Rule
@@ -953,10 +951,7 @@ namespace YooAsset.Editor
{
collector.FilterRuleName = evt.newValue.ClassName;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
RefreshFoldoutContent(foldout, selectGroup, collector);
});
// UserData
@@ -977,61 +972,101 @@ namespace YooAsset.Editor
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
});
}
private void RefreshFoldout(Foldout foldout, AssetBundleCollectorGroup group, AssetBundleCollector collector)
private void RefreshFoldoutName(Foldout foldout, ECollectorType collectorType, int elementNumber = -1)
{
if (collectorType == ECollectorType.MainAssetCollector)
{
if (elementNumber >= 0)
foldout.text = $"Main Assets ({elementNumber})";
else
foldout.text = $"Main Assets";
}
else if (collectorType == ECollectorType.StaticAssetCollector)
{
if (elementNumber >= 0)
foldout.text = $"Static Assets ({elementNumber})";
else
foldout.text = $"Static Assets";
}
else if (collectorType == ECollectorType.DependAssetCollector)
{
if (elementNumber >= 0)
foldout.text = $"Depend Assets ({elementNumber})";
else
foldout.text = $"Depend Assets";
}
else
{
throw new System.NotImplementedException(collectorType.ToString());
}
}
private void RefreshFoldoutContent(Foldout foldout, AssetBundleCollectorGroup group, AssetBundleCollector collector)
{
RefreshFoldoutName(foldout, collector.CollectorType);
// 折叠栏不可见
if (foldout.value == false)
{
foldout.Clear();
return;
}
// 清空旧元素
foldout.Clear();
// 检测配置是否有效
if (collector.IsValid() == false)
{
collector.CheckConfigError();
return;
}
if (collector.CollectorType == ECollectorType.MainAssetCollector || collector.CollectorType == ECollectorType.StaticAssetCollector)
List<CollectAssetInfo> collectAssetInfos = null;
try
{
List<CollectAssetInfo> collectAssetInfos = null;
IIgnoreRule ignoreRule = AssetBundleCollectorSettingData.GetIgnoreRuleInstance(_ignoreRulePopupField.value.ClassName);
string packageName = _packageNameTxt.value;
var command = new CollectCommand(packageName, ignoreRule);
command.SetFlag(ECollectFlags.IgnoreGetDependencies, true);
command.UniqueBundleName = _uniqueBundleNameToogle.value;
command.EnableAddressable = _enableAddressableToogle.value;
command.SupportExtensionless = _supportExtensionlessToogle.value;
command.LocationToLower = _locationToLowerToogle.value;
command.IncludeAssetGUID = _includeAssetGUIDToogle.value;
command.AutoCollectShaders = _autoCollectShadersToogle.value;
try
collector.CheckConfigError();
collectAssetInfos = collector.GetAllCollectAssets(command, group);
}
catch (System.Exception e)
{
Debug.LogError(e.ToString());
}
if (collectAssetInfos != null)
{
bool showAdress = false;
if (_enableAddressableToogle.value && collector.CollectorType == ECollectorType.MainAssetCollector)
showAdress = true;
RefreshFoldoutName(foldout, collector.CollectorType, collectAssetInfos.Count);
foreach (var collectAsset in collectAssetInfos)
{
IIgnoreRule ignoreRule = AssetBundleCollectorSettingData.GetIgnoreRuleInstance(_ignoreRulePopupField.value.ClassName);
string packageName = _packageNameTxt.value;
var command = new CollectCommand(packageName, ignoreRule);
command.SimulateBuild = true;
command.UniqueBundleName = _uniqueBundleNameToogle.value;
command.UseAssetDependencyDB = true;
command.EnableAddressable = _enableAddressableToogle.value;
command.LocationToLower = _locationToLowerToogle.value;
command.IncludeAssetGUID = _includeAssetGUIDToogle.value;
command.AutoCollectShaders = _autoCollectShadersToogle.value;
VisualElement elementRow = new VisualElement();
elementRow.style.flexDirection = FlexDirection.Row;
foldout.Add(elementRow);
collector.CheckConfigError();
collectAssetInfos = collector.GetAllCollectAssets(command, group);
}
catch (System.Exception e)
{
Debug.LogError(e.ToString());
}
string showInfo = collectAsset.AssetInfo.AssetPath;
if (showAdress)
showInfo = $"[{collectAsset.Address}] {collectAsset.AssetInfo.AssetPath}";
if (collectAssetInfos != null)
{
foreach (var collectAsset in collectAssetInfos)
{
VisualElement elementRow = new VisualElement();
elementRow.style.flexDirection = FlexDirection.Row;
foldout.Add(elementRow);
string showInfo = collectAsset.AssetInfo.AssetPath;
if (_enableAddressableToogle.value)
showInfo = $"[{collectAsset.Address}] {collectAsset.AssetInfo.AssetPath}";
var label = new Label();
label.text = showInfo;
label.style.width = 300;
label.style.marginLeft = 0;
label.style.flexGrow = 1;
elementRow.Add(label);
}
var label = new Label();
label.text = showInfo;
label.style.width = 300;
label.style.marginLeft = 0;
label.style.flexGrow = 1;
elementRow.Add(label);
}
}
}

View File

@@ -19,6 +19,7 @@
<ui:Button text="Package Settings" display-tooltip-when-elided="true" name="PackageSettingsButton" />
<ui:VisualElement name="PublicContainer2">
<ui:Toggle label="Enable Addressable" name="EnableAddressable" style="width: 196px; -unity-text-align: middle-left;" />
<ui:Toggle label="Support Extensionless" name="SupportExtensionless" style="width: 196px; -unity-text-align: middle-left;" />
<ui:Toggle label="Location To Lower" name="LocationToLower" style="width: 196px; -unity-text-align: middle-left;" />
<ui:Toggle label="Include Asset GUID" name="IncludeAssetGUID" style="width: 196px; -unity-text-align: middle-left;" />
<ui:Toggle label="Auto Collect Shaders" name="AutoCollectShaders" value="true" style="width: 196px; -unity-text-align: middle-left;" />

View File

@@ -177,19 +177,21 @@ namespace YooAsset.Editor
/// </summary>
public string[] GetDependencies(string assetPath, bool recursive)
{
// 注意AssetDatabase.GetDependencies()方法返回结果里会踢出丢失文件!
// 注意AssetDatabase.GetDependencies()方法返回结果里会包含主资源路径!
// 注意:机制上不允许存在未收录的资源
if (_database.ContainsKey(assetPath) == false)
{
throw new Exception($"Fatal : can not found cache info : {assetPath}");
}
var result = new HashSet<string> { assetPath };
var result = new HashSet<string>();
// 注意:递归收集依赖时,依赖列表中包含主资源
if (recursive)
result.Add(assetPath);
// 收集依赖
CollectDependencies(assetPath, assetPath, result, recursive);
// 注意AssetDatabase.GetDependencies保持一致将主资源添加到依赖列表最前面
return result.ToArray();
}
private void CollectDependencies(string parent, string assetPath, HashSet<string> result, bool recursive)
@@ -255,6 +257,7 @@ namespace YooAsset.Editor
}
private DependencyInfo CreateDependencyInfo(string assetPath)
{
// 注意AssetDatabase.GetDependencies()方法返回结果里会踢出丢失文件!
var dependHash = AssetDatabase.GetAssetDependencyHash(assetPath);
var dependAssetPaths = AssetDatabase.GetDependencies(assetPath, false);
var dependGUIDs = new List<string>();

View File

@@ -1,6 +1,26 @@

namespace YooAsset.Editor
{
public enum ECollectFlags
{
None = 0,
/// <summary>
/// 不收集依赖资源
/// </summary>
IgnoreGetDependencies = 1 << 0,
/// <summary>
/// 忽略静态收集器
/// </summary>
IgnoreStaticCollector = 1 << 1,
/// <summary>
/// 忽略依赖收集器
/// </summary>
IgnoreDependCollector = 1 << 2,
}
public class CollectCommand
{
/// <summary>
@@ -17,7 +37,20 @@ namespace YooAsset.Editor
/// <summary>
/// 模拟构建模式
/// </summary>
public bool SimulateBuild { set; get; }
public bool SimulateBuild
{
set
{
SetFlag(ECollectFlags.IgnoreGetDependencies, value);
SetFlag(ECollectFlags.IgnoreStaticCollector, value);
SetFlag(ECollectFlags.IgnoreDependCollector, value);
}
}
/// <summary>
/// 窗口收集模式
/// </summary>
public int CollectFlags { set; get; } = 0;
/// <summary>
/// 资源包名唯一化
@@ -34,6 +67,11 @@ namespace YooAsset.Editor
/// </summary>
public bool EnableAddressable { set; get; }
/// <summary>
/// 支持无后缀名的资源定位地址
/// </summary>
public bool SupportExtensionless { set; get; }
/// <summary>
/// 资源定位地址大小写不敏感
/// </summary>
@@ -65,5 +103,24 @@ namespace YooAsset.Editor
PackageName = packageName;
IgnoreRule = ignoreRule;
}
/// <summary>
/// 设置标记位
/// </summary>
public void SetFlag(ECollectFlags flag, bool isOn)
{
if (isOn)
CollectFlags |= (int)flag; // 开启指定标志位
else
CollectFlags &= ~(int)flag; // 关闭指定标志位
}
/// <summary>
/// 查询标记位
/// </summary>
public bool IsFlagSet(ECollectFlags flag)
{
return (CollectFlags & (int)flag) != 0;
}
}
}

View File

@@ -23,7 +23,13 @@ namespace YooAsset.Editor
public interface IFilterRule
{
/// <summary>
/// 是否为收集资源
/// 搜寻的资源类型
/// 说明:使用引擎方法搜索获取所有资源列表
/// </summary>
string FindAssetType { get; }
/// <summary>
/// 验证搜寻的资源是否为收集资源
/// </summary>
/// <returns>如果收集该资源返回TRUE</returns>
bool IsCollectAsset(FilterRuleData data);

View File

@@ -9,6 +9,11 @@ namespace YooAsset.Editor
[DisplayName("收集所有资源")]
public class CollectAll : IFilterRule
{
public string FindAssetType
{
get { return EAssetSearchType.All.ToString(); }
}
public bool IsCollectAsset(FilterRuleData data)
{
return true;
@@ -18,6 +23,11 @@ namespace YooAsset.Editor
[DisplayName("收集场景")]
public class CollectScene : IFilterRule
{
public string FindAssetType
{
get { return EAssetSearchType.Scene.ToString(); }
}
public bool IsCollectAsset(FilterRuleData data)
{
string extension = Path.GetExtension(data.AssetPath);
@@ -28,6 +38,11 @@ namespace YooAsset.Editor
[DisplayName("收集预制体")]
public class CollectPrefab : IFilterRule
{
public string FindAssetType
{
get { return EAssetSearchType.Prefab.ToString(); }
}
public bool IsCollectAsset(FilterRuleData data)
{
return Path.GetExtension(data.AssetPath) == ".prefab";
@@ -37,6 +52,11 @@ namespace YooAsset.Editor
[DisplayName("收集精灵类型的纹理")]
public class CollectSprite : IFilterRule
{
public string FindAssetType
{
get { return EAssetSearchType.Sprite.ToString(); }
}
public bool IsCollectAsset(FilterRuleData data)
{
var mainAssetType = AssetDatabase.GetMainAssetTypeAtPath(data.AssetPath);
@@ -58,6 +78,11 @@ namespace YooAsset.Editor
[DisplayName("收集着色器")]
public class CollectShader : IFilterRule
{
public string FindAssetType
{
get { return EAssetSearchType.Shader.ToString(); }
}
public bool IsCollectAsset(FilterRuleData data)
{
return Path.GetExtension(data.AssetPath) == ".shader";
@@ -67,6 +92,11 @@ namespace YooAsset.Editor
[DisplayName("收集着色器变种集合")]
public class CollectShaderVariants : IFilterRule
{
public string FindAssetType
{
get { return EAssetSearchType.All.ToString(); }
}
public bool IsCollectAsset(FilterRuleData data)
{
return Path.GetExtension(data.AssetPath) == ".shadervariants";

View File

@@ -17,16 +17,25 @@ namespace YooAsset.Editor
public const string RawFileExtension = "rawfile";
/// <summary>
/// Unity着色器资源包名称
/// 默认的Unity着色器资源包名称
/// </summary>
public const string ShadersBundleName = "unityshaders";
/// <summary>
/// 默认的Unity脚本资源包名称
/// </summary>
public const string MonosBundleName = "unitymonos";
public static PackRuleResult CreateShadersPackRuleResult()
{
PackRuleResult result = new PackRuleResult(ShadersBundleName, AssetBundleFileExtension);
return result;
}
public static PackRuleResult CreateMonosPackRuleResult()
{
PackRuleResult result = new PackRuleResult(MonosBundleName, AssetBundleFileExtension);
return result;
}
}
/// <summary>

View File

@@ -26,7 +26,7 @@ namespace YooAsset.Editor
/// <summary>
/// 文件校验码
/// </summary>
public string FileCRC;
public uint FileCRC;
/// <summary>
/// 文件大小(字节数)

View File

@@ -61,6 +61,7 @@ namespace YooAsset.Editor
// 收集器配置
public bool UniqueBundleName;
public bool EnableAddressable;
public bool SupportExtensionless;
public bool LocationToLower;
public bool IncludeAssetGUID;
public bool AutoCollectShaders;
@@ -71,9 +72,11 @@ namespace YooAsset.Editor
public bool UseAssetDependencyDB;
public bool EnableSharePackRule;
public bool SingleReferencedPackAlone;
public string EncryptionClassName;
public string EncryptionServicesClassName;
public string ManifestProcessServicesClassName;
public string ManifestRestoreServicesClassName;
public EFileNameStyle FileNameStyle;
// 引擎参数
public ECompressOption CompressOption;
public bool DisableWriteTypeTree;

View File

@@ -55,6 +55,7 @@ namespace YooAsset.Editor
BindListViewHeader("Collect Settings");
BindListViewItem("Unique Bundle Name", $"{buildReport.Summary.UniqueBundleName}");
BindListViewItem("Enable Addressable", $"{buildReport.Summary.EnableAddressable}");
BindListViewItem("Support Extensionless", $"{buildReport.Summary.SupportExtensionless}");
BindListViewItem("Location To Lower", $"{buildReport.Summary.LocationToLower}");
BindListViewItem("Include Asset GUID", $"{buildReport.Summary.IncludeAssetGUID}");
BindListViewItem("Auto Collect Shaders", $"{buildReport.Summary.AutoCollectShaders}");
@@ -66,7 +67,9 @@ namespace YooAsset.Editor
BindListViewItem("Use Asset Dependency DB", $"{buildReport.Summary.UseAssetDependencyDB}");
BindListViewItem("Enable Share Pack Rule", $"{buildReport.Summary.EnableSharePackRule}");
BindListViewItem("Single Referenced Pack Alone", $"{buildReport.Summary.SingleReferencedPackAlone}");
BindListViewItem("Encryption Class Name", buildReport.Summary.EncryptionClassName);
BindListViewItem("Encryption Services", buildReport.Summary.EncryptionServicesClassName);
BindListViewItem("Manifest Process Services", buildReport.Summary.ManifestProcessServicesClassName);
BindListViewItem("Manifest Restore Services", buildReport.Summary.ManifestRestoreServicesClassName);
BindListViewItem("FileNameStyle", $"{buildReport.Summary.FileNameStyle}");
BindListViewItem("CompressOption", $"{buildReport.Summary.CompressOption}");
BindListViewItem("DisableWriteTypeTree", $"{buildReport.Summary.DisableWriteTypeTree}");

View File

@@ -62,6 +62,17 @@ namespace YooAsset.Editor
return false;
}
/// <summary>
/// 是否为图集资源
/// </summary>
public bool IsSpriteAtlas()
{
if (AssetType == typeof(UnityEngine.U2D.SpriteAtlas))
return true;
else
return false;
}
public int CompareTo(AssetInfo other)
{
return this.AssetPath.CompareTo(other.AssetPath);

View File

@@ -39,6 +39,7 @@ namespace YooAsset.Editor
Shader,
Sprite,
Texture,
RenderTexture,
VideoClip,
}

View File

@@ -169,6 +169,28 @@ namespace YooAsset.Editor
/// <param name="searchInFolders">指定搜索的文件夹列表</param>
/// <returns>返回搜集到的资源路径列表</returns>
public static string[] FindAssets(EAssetSearchType searchType, string[] searchInFolders)
{
return FindAssets(searchType.ToString(), searchInFolders);
}
/// <summary>
/// 搜集资源
/// </summary>
/// <param name="searchType">搜集的资源类型</param>
/// <param name="searchInFolder">指定搜索的文件夹</param>
/// <returns>返回搜集到的资源路径列表</returns>
public static string[] FindAssets(EAssetSearchType searchType, string searchInFolder)
{
return FindAssets(searchType.ToString(), new string[] { searchInFolder });
}
/// <summary>
/// 搜集资源
/// </summary>
/// <param name="searchType">搜集的资源类型</param>
/// <param name="searchInFolders">指定搜索的文件夹列表</param>
/// <returns>返回搜集到的资源路径列表</returns>
public static string[] FindAssets(string searchType, string[] searchInFolders)
{
// 注意AssetDatabase.FindAssets()不支持末尾带分隔符的文件夹路径
for (int i = 0; i < searchInFolders.Length; i++)
@@ -179,7 +201,7 @@ namespace YooAsset.Editor
// 注意:获取指定目录下的所有资源对象(包括子文件夹)
string[] guids;
if (searchType == EAssetSearchType.All)
if (string.IsNullOrEmpty(searchType) || searchType == EAssetSearchType.All.ToString())
guids = AssetDatabase.FindAssets(string.Empty, searchInFolders);
else
guids = AssetDatabase.FindAssets($"t:{searchType}", searchInFolders);
@@ -206,7 +228,7 @@ namespace YooAsset.Editor
/// <param name="searchType">搜集的资源类型</param>
/// <param name="searchInFolder">指定搜索的文件夹</param>
/// <returns>返回搜集到的资源路径列表</returns>
public static string[] FindAssets(EAssetSearchType searchType, string searchInFolder)
public static string[] FindAssets(string searchType, string searchInFolder)
{
return FindAssets(searchType, new string[] { searchInFolder });
}

View File

@@ -33,6 +33,67 @@ namespace YooAsset.Editor
}
}
/// <summary>
/// 设置元素显示文本为资源路径
/// </summary>
public static void SetObjectFieldShowPath(ObjectField objectField)
{
string LabelClassName = "unity-object-field-display__label";
var nameLable = objectField.Q<Label>(className: LabelClassName);
if (nameLable == null)
return;
objectField.RegisterValueChangedCallback(evt =>
{
Object obj = evt.newValue;
if (obj == null)
{
nameLable.text = "None (Object)";
return;
}
// 获取资源路径(仅适用于项目资源)
string path = AssetDatabase.GetAssetPath(obj);
if (string.IsNullOrEmpty(path) == false)
{
nameLable.text = path;
}
else
{
nameLable.text = obj.name;
}
});
}
/// <summary>
/// 刷新元素显示文本内容
/// </summary>
public static void RefreshObjectFieldShowPath(ObjectField objectField)
{
string LabelClassName = "unity-object-field-display__label";
var nameLable = objectField.Q<Label>(className: LabelClassName);
if (nameLable == null)
return;
Object obj = objectField.value;
if (obj == null)
{
nameLable.text = "None (Object)";
return;
}
// 获取资源路径(仅适用于项目资源)
string path = AssetDatabase.GetAssetPath(obj);
if (string.IsNullOrEmpty(path) == false)
{
nameLable.text = path;
}
else
{
nameLable.text = obj.name;
}
}
/// <summary>
/// 设置按钮图标
/// </summary>

View File

@@ -2,6 +2,7 @@
// 内部友元
[assembly: InternalsVisibleTo("YooAsset.Editor")]
[assembly: InternalsVisibleTo("YooAsset.Test")]
[assembly: InternalsVisibleTo("YooAsset.Test.Editor")]
// 外部友元

View File

@@ -94,4 +94,25 @@ namespace YooAsset
/// </summary>
public long FileSize;
}
/// <summary>
/// 导入文件的信息
/// </summary>
public struct ImportFileInfo
{
/// <summary>
/// 本地文件路径
/// </summary>
public string FilePath;
/// <summary>
/// 资源包名称
/// </summary>
public string BundleName;
/// <summary>
/// 资源包GUID
/// </summary>
public string BundleGUID;
}
}

View File

@@ -37,13 +37,17 @@ namespace YooAsset
string url;
// 获取对应平台的URL地址
// 说明:苹果不同设备上操作系统不同。
// 说明iPhone和iPod对应的是iOS系统。
// 说明iPad对应的是iPadOS系统。
// 说明AppleTV对应的是tvOS系统。
#if UNITY_EDITOR_OSX
url = StringUtility.Format("file://{0}", path);
#elif UNITY_EDITOR
#elif UNITY_EDITOR_WIN
url = StringUtility.Format("file:///{0}", path);
#elif UNITY_WEBGL
url = path;
#elif UNITY_IPHONE
#elif UNITY_IOS || UNITY_IPHONE
url = StringUtility.Format("file://{0}", path);
#elif UNITY_ANDROID
if (path.StartsWith("jar:file://"))
@@ -65,12 +69,17 @@ namespace YooAsset
else
url = StringUtility.Format("file://{0}", path);
}
#elif UNITY_STANDALONE_OSX
url = new System.Uri(path).ToString();
#elif UNITY_STANDALONE || UNITY_WSA
#elif UNITY_WSA
url = StringUtility.Format("file:///{0}", path);
#elif UNITY_TVOS
url = StringUtility.Format("file:///{0}", path);
#elif UNITY_STANDALONE_OSX
url = new System.Uri(path).ToString();
#elif UNITY_STANDALONE_WIN
url = StringUtility.Format("file:///{0}", path);
#elif UNITY_STANDALONE_LINUX
url = StringUtility.Format("file:///root/{0}", path);
#else
throw new System.NotImplementedException();
#endif

View File

@@ -1,16 +1,32 @@
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Networking;
using UnityEngine;
namespace YooAsset
{
internal class DownloadWebNormalAssetBundleOperation : DownloadAssetBundleOperation
internal class UnityAssetBundleRequestOperation : UnityWebRequestOperation
{
private readonly bool _disableUnityWebCache;
protected enum ESteps
{
None,
CreateRequest,
Download,
Done,
}
private UnityWebRequestAsyncOperation _requestOperation;
private DownloadHandlerAssetBundle _downloadhandler;
private readonly PackageBundle _packageBundle;
private readonly bool _disableUnityWebCache;
private ESteps _steps = ESteps.None;
internal DownloadWebNormalAssetBundleOperation(bool disableUnityWebCache, PackageBundle bundle, DownloadFileOptions options) : base(bundle, options)
/// <summary>
/// 请求结果
/// </summary>
public AssetBundle Result { private set; get; }
internal UnityAssetBundleRequestOperation(PackageBundle packageBundle, bool disableUnityWebCache, string url) : base(url)
{
_packageBundle = packageBundle;
_disableUnityWebCache = disableUnityWebCache;
}
internal override void InternalStart()
@@ -22,34 +38,20 @@ namespace YooAsset
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
// 创建下载器
if (_steps == ESteps.CreateRequest)
{
// 获取请求地址
_requestURL = GetRequestURL();
// 重置变量
ResetRequestFiled();
// 创建下载器
CreateWebRequest();
_steps = ESteps.CheckRequest;
_steps = ESteps.Download;
}
// 检测下载结果
if (_steps == ESteps.CheckRequest)
if (_steps == ESteps.Download)
{
DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = (long)_webRequest.downloadedBytes;
Progress = DownloadProgress;
if (_webRequest.isDone == false)
{
CheckRequestTimeout();
Progress = _requestOperation.progress;
if (_requestOperation.isDone == false)
return;
}
// 检查网络错误
if (CheckRequestResult())
{
AssetBundle assetBundle = _downloadhandler.assetBundle;
@@ -57,7 +59,7 @@ namespace YooAsset
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = "Download handler asset bundle object is null !";
Error = $"URL : {_requestURL} Download handler asset bundle object is null !";
}
else
{
@@ -68,37 +70,13 @@ namespace YooAsset
}
else
{
_steps = ESteps.TryAgain;
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
}
// 注意:最终释放请求器
DisposeWebRequest();
DisposeRequest();
}
// 重新尝试下载
if (_steps == ESteps.TryAgain)
{
if (FailedTryAgain <= 0)
{
Status = EOperationStatus.Failed;
_steps = ESteps.Done;
YooLogger.Error(Error);
return;
}
_tryAgainTimer += Time.unscaledDeltaTime;
if (_tryAgainTimer > 1f)
{
FailedTryAgain--;
_steps = ESteps.CreateRequest;
YooLogger.Warning(Error);
}
}
}
internal override void InternalAbort()
{
_steps = ESteps.Done;
DisposeWebRequest();
}
private void CreateWebRequest()
@@ -107,22 +85,13 @@ namespace YooAsset
_webRequest = DownloadSystemHelper.NewUnityWebRequestGet(_requestURL);
_webRequest.downloadHandler = _downloadhandler;
_webRequest.disposeDownloadHandlerOnDispose = true;
_webRequest.SendWebRequest();
}
private void DisposeWebRequest()
{
if (_webRequest != null)
{
//注意引擎底层会自动调用Abort方法
_webRequest.Dispose();
_webRequest = null;
}
_requestOperation = _webRequest.SendWebRequest();
}
private DownloadHandlerAssetBundle CreateWebDownloadHandler()
{
if (_disableUnityWebCache)
{
var downloadhandler = new DownloadHandlerAssetBundle(_requestURL, Bundle.UnityCRC);
var downloadhandler = new DownloadHandlerAssetBundle(_requestURL, _packageBundle.UnityCRC);
#if UNITY_2020_3_OR_NEWER
downloadhandler.autoLoadAssetBundle = false;
#endif
@@ -132,8 +101,8 @@ namespace YooAsset
{
// 注意:优先从浏览器缓存里获取文件
// The file hash defining the version of the asset bundle.
Hash128 fileHash = Hash128.Parse(Bundle.FileHash);
var downloadhandler = new DownloadHandlerAssetBundle(_requestURL, fileHash, Bundle.UnityCRC);
Hash128 fileHash = Hash128.Parse(_packageBundle.FileHash);
var downloadhandler = new DownloadHandlerAssetBundle(_requestURL, fileHash, _packageBundle.UnityCRC);
#if UNITY_2020_3_OR_NEWER
downloadhandler.autoLoadAssetBundle = false;
#endif

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: f2a5bb0106a45e540a43a05b72a75bcd
guid: e01cc308d7179a34281087fafe455b42
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@@ -0,0 +1,65 @@
using UnityEngine.Networking;
using UnityEngine;
namespace YooAsset
{
internal class UnityVirtualBundleRequestOperation : UnityWebRequestOperation
{
protected enum ESteps
{
None,
Download,
Done,
}
private readonly PackageBundle _bundle;
private readonly int _downloadSpeed;
private ESteps _steps = ESteps.None;
internal UnityVirtualBundleRequestOperation(PackageBundle packageBundle, int downloadSpeed, string url) : base(url)
{
_bundle = packageBundle;
_downloadSpeed = downloadSpeed;
}
internal override void InternalStart()
{
_steps = ESteps.Download;
}
internal override void InternalUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.Download)
{
// 模拟下载进度
float progress = 0;
if (DownloadedBytes > 0)
progress = DownloadedBytes / _bundle.FileSize;
long downloadBytes = (long)((double)_downloadSpeed * Time.deltaTime);
Progress = progress;
DownloadProgress = progress;
DownloadedBytes += downloadBytes;
if (DownloadedBytes < _bundle.FileSize)
return;
Progress = 1f;
DownloadProgress = 1f;
DownloadedBytes = _bundle.FileSize;
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
}
internal override void InternalWaitForAsyncComplete()
{
if (_steps != ESteps.Done)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Try load bundle {_bundle.BundleName} from remote !";
}
}
}
}

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 69f62f6b4185d06498f96aa272e9b926
guid: 9e71e850eded0da43906cb4f7cb75629
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@@ -0,0 +1,89 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Networking;
using UnityEngine;
namespace YooAsset
{
internal class UnityWebCacheRequestOperation : UnityWebRequestOperation
{
protected enum ESteps
{
None,
CreateRequest,
Download,
Done,
}
private UnityWebRequestAsyncOperation _requestOperation;
private readonly Dictionary<string, string> _headers = new Dictionary<string, string>();
private ESteps _steps = ESteps.None;
internal UnityWebCacheRequestOperation(string url) : base(url)
{
}
internal override void InternalStart()
{
_steps = ESteps.CreateRequest;
}
internal override void InternalUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.CreateRequest)
{
CreateWebRequest();
_steps = ESteps.Download;
}
if (_steps == ESteps.Download)
{
DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = (long)_webRequest.downloadedBytes;
Progress = _requestOperation.progress;
if (_requestOperation.isDone == false)
return;
if (CheckRequestResult())
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
}
// 注意:最终释放请求器
DisposeRequest();
}
}
/// <summary>
/// 设置请求头信息
/// </summary>
public void SetRequestHeader(string name, string value)
{
_headers.Add(name, value);
}
private void CreateWebRequest()
{
_webRequest = DownloadSystemHelper.NewUnityWebRequestGet(_requestURL);
_webRequest.disposeDownloadHandlerOnDispose = true;
// 设置消息头
foreach (var keyValuePair in _headers)
{
string name = keyValuePair.Key;
string value = keyValuePair.Value;
_webRequest.SetRequestHeader(name, value);
}
_requestOperation = _webRequest.SendWebRequest();
}
}
}

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 8ac57bde14f2e1a4e9323751a7157ed7
guid: 375d88bcf5b9a6146adaf98ceb5369f8
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@@ -5,7 +5,23 @@ namespace YooAsset
{
internal class UnityWebDataRequestOperation : UnityWebRequestOperation
{
protected enum ESteps
{
None,
CreateRequest,
Download,
Done,
}
private UnityWebRequestAsyncOperation _requestOperation;
private ESteps _steps = ESteps.None;
/// <summary>
/// 响应的超时时间单位在经过Timeout的秒数后尝试中止。
/// 注意当Timeout设置为0时不会应用超时。
/// 注意设置的超时值可能应用于Android上的每个URL重定向这可能会导致响应时间增加。
/// </summary>
private readonly int _timeout;
/// <summary>
/// 请求结果
@@ -13,8 +29,9 @@ namespace YooAsset
public byte[] Result { private set; get; }
internal UnityWebDataRequestOperation(string url, int timeout = 60) : base(url, timeout)
internal UnityWebDataRequestOperation(string url, int timeout) : base(url)
{
_timeout = timeout;
}
internal override void InternalStart()
{
@@ -27,27 +44,33 @@ namespace YooAsset
if (_steps == ESteps.CreateRequest)
{
_latestDownloadBytes = 0;
_latestDownloadRealtime = Time.realtimeSinceStartup;
CreateWebRequest();
_steps = ESteps.Download;
}
if (_steps == ESteps.Download)
{
DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = (long)_webRequest.downloadedBytes;
Progress = _requestOperation.progress;
if (_requestOperation.isDone == false)
{
CheckRequestTimeout();
return;
}
if (CheckRequestResult())
{
_steps = ESteps.Done;
Result = _webRequest.downloadHandler.data;
Status = EOperationStatus.Succeed;
var fileData = _webRequest.downloadHandler.data;
if (fileData == null || fileData.Length == 0)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"URL : {_requestURL} Download handler data is null or empty !";
}
else
{
_steps = ESteps.Done;
Result = fileData;
Status = EOperationStatus.Succeed;
}
}
else
{
@@ -59,16 +82,12 @@ namespace YooAsset
DisposeRequest();
}
}
internal override void InternalAbort()
{
_steps = ESteps.Done;
DisposeRequest();
}
private void CreateWebRequest()
{
_webRequest = DownloadSystemHelper.NewUnityWebRequestGet(_requestURL);
DownloadHandlerBuffer handler = new DownloadHandlerBuffer();
_webRequest = DownloadSystemHelper.NewUnityWebRequestGet(_requestURL);
_webRequest.timeout = _timeout;
_webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true;
_requestOperation = _webRequest.SendWebRequest();

View File

@@ -5,12 +5,30 @@ namespace YooAsset
{
internal class UnityWebFileRequestOperation : UnityWebRequestOperation
{
protected enum ESteps
{
None,
CreateRequest,
Download,
Done,
}
private UnityWebRequestAsyncOperation _requestOperation;
private readonly string _fileSavePath;
private ESteps _steps = ESteps.None;
internal UnityWebFileRequestOperation(string url, string fileSavePath, int timeout = 60) : base(url, timeout)
/// <summary>
/// 响应的超时时间单位在经过Timeout的秒数后尝试中止。
/// 注意当Timeout设置为0时不会应用超时。
/// 注意设置的超时值可能应用于Android上的每个URL重定向这可能会导致响应时间增加。
/// </summary>
private readonly int _timeout;
internal UnityWebFileRequestOperation(string url, string fileSavePath, int timeout) : base(url)
{
_fileSavePath = fileSavePath;
_timeout = timeout;
}
internal override void InternalStart()
{
@@ -23,21 +41,17 @@ namespace YooAsset
if (_steps == ESteps.CreateRequest)
{
_latestDownloadBytes = 0;
_latestDownloadRealtime = Time.realtimeSinceStartup;
CreateWebRequest();
_steps = ESteps.Download;
}
if (_steps == ESteps.Download)
{
DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = (long)_webRequest.downloadedBytes;
Progress = _requestOperation.progress;
if (_requestOperation.isDone == false)
{
CheckRequestTimeout();
return;
}
if (CheckRequestResult())
{
@@ -54,17 +68,13 @@ namespace YooAsset
DisposeRequest();
}
}
internal override void InternalAbort()
{
_steps = ESteps.Done;
DisposeRequest();
}
private void CreateWebRequest()
{
_webRequest = DownloadSystemHelper.NewUnityWebRequestGet(_requestURL);
DownloadHandlerFile handler = new DownloadHandlerFile(_fileSavePath);
handler.removeFileOnAbort = true;
_webRequest = DownloadSystemHelper.NewUnityWebRequestGet(_requestURL);
_webRequest.timeout = _timeout;
_webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true;
_requestOperation = _webRequest.SendWebRequest();

View File

@@ -1,6 +1,4 @@
using System;
using System.Collections;
using System.Collections.Concurrent;
using UnityEngine.Networking;
using UnityEngine;
@@ -8,33 +6,50 @@ namespace YooAsset
{
internal abstract class UnityWebRequestOperation : AsyncOperationBase
{
protected enum ESteps
{
None,
CreateRequest,
Download,
Done,
}
protected UnityWebRequest _webRequest;
protected readonly string _requestURL;
protected ESteps _steps = ESteps.None;
// 超时相关
protected readonly float _timeout;
protected ulong _latestDownloadBytes;
protected float _latestDownloadRealtime;
private bool _isAbort = false;
/// <summary>
/// HTTP返回码
/// </summary>
public long HttpCode { private set; get; }
/// <summary>
/// 当前下载的字节数
/// </summary>
public long DownloadedBytes { protected set; get; }
/// <summary>
/// 当前下载进度0f - 1f
/// </summary>
public float DownloadProgress { protected set; get; }
/// <summary>
/// 请求的URL地址
/// </summary>
public string URL
{
get { return _requestURL; }
}
internal UnityWebRequestOperation(string url, int timeout)
internal UnityWebRequestOperation(string url)
{
_requestURL = url;
_timeout = timeout;
}
internal override void InternalAbort()
{
//TODO
// 1. 编辑器下停止运行游戏的时候主动终止下载任务
// 2. 真机上销毁包裹的时候主动终止下载任务
if (_isAbort == false)
{
if (_webRequest != null)
{
_webRequest.Abort();
_isAbort = true;
}
}
}
/// <summary>
@@ -44,39 +59,19 @@ namespace YooAsset
{
if (_webRequest != null)
{
//注意引擎底层会自动调用Abort方法
_webRequest.Dispose();
_webRequest = null;
}
}
/// <summary>
/// 检测超时
/// </summary>
protected void CheckRequestTimeout()
{
// 注意:在连续时间段内无新增下载数据及判定为超时
if (_isAbort == false)
{
if ( _latestDownloadBytes != _webRequest.downloadedBytes)
{
_latestDownloadBytes = _webRequest.downloadedBytes;
_latestDownloadRealtime = Time.realtimeSinceStartup;
}
float offset = Time.realtimeSinceStartup - _latestDownloadRealtime;
if (offset > _timeout)
{
_webRequest.Abort();
_isAbort = true;
}
}
}
/// <summary>
/// 检测请求结果
/// </summary>
protected bool CheckRequestResult()
{
HttpCode = _webRequest.responseCode;
#if UNITY_2020_3_OR_NEWER
if (_webRequest.result != UnityWebRequest.Result.Success)
{

View File

@@ -5,7 +5,23 @@ namespace YooAsset
{
internal class UnityWebTextRequestOperation : UnityWebRequestOperation
{
protected enum ESteps
{
None,
CreateRequest,
Download,
Done,
}
private UnityWebRequestAsyncOperation _requestOperation;
private ESteps _steps = ESteps.None;
/// <summary>
/// 响应的超时时间单位在经过Timeout的秒数后尝试中止。
/// 注意当Timeout设置为0时不会应用超时。
/// 注意设置的超时值可能应用于Android上的每个URL重定向这可能会导致响应时间增加。
/// </summary>
private readonly int _timeout;
/// <summary>
/// 请求结果
@@ -13,8 +29,9 @@ namespace YooAsset
public string Result { private set; get; }
internal UnityWebTextRequestOperation(string url, int timeout = 60) : base(url, timeout)
internal UnityWebTextRequestOperation(string url, int timeout) : base(url)
{
_timeout = timeout;
}
internal override void InternalStart()
{
@@ -27,27 +44,33 @@ namespace YooAsset
if (_steps == ESteps.CreateRequest)
{
_latestDownloadBytes = 0;
_latestDownloadRealtime = Time.realtimeSinceStartup;
CreateWebRequest();
_steps = ESteps.Download;
}
if (_steps == ESteps.Download)
{
DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = (long)_webRequest.downloadedBytes;
Progress = _requestOperation.progress;
if (_requestOperation.isDone == false)
{
CheckRequestTimeout();
return;
}
if (CheckRequestResult())
{
_steps = ESteps.Done;
Result = _webRequest.downloadHandler.text;
Status = EOperationStatus.Succeed;
var fileText = _webRequest.downloadHandler.text;
if (string.IsNullOrEmpty(fileText))
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"URL : {_requestURL} Download handler text is null or empty !";
}
else
{
_steps = ESteps.Done;
Result = fileText;
Status = EOperationStatus.Succeed;
}
}
else
{
@@ -59,16 +82,12 @@ namespace YooAsset
DisposeRequest();
}
}
internal override void InternalAbort()
{
_steps = ESteps.Done;
DisposeRequest();
}
private void CreateWebRequest()
{
_webRequest = DownloadSystemHelper.NewUnityWebRequestGet(_requestURL);
DownloadHandlerBuffer handler = new DownloadHandlerBuffer();
_webRequest = DownloadSystemHelper.NewUnityWebRequestGet(_requestURL);
_webRequest.timeout = _timeout;
_webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true;
_requestOperation = _webRequest.SendWebRequest();

View File

@@ -106,7 +106,7 @@ namespace YooAsset
}
internal override void InternalWaitForAsyncComplete()
{
//TODO 场景加载不支持异步转同步,为了支持同步加载方法需要实现该方法!
//注意:场景加载不支持异步转同步,为了支持同步加载方法需要实现该方法!
InternalUpdate();
}
public override void UnSuspendLoad()

View File

@@ -112,7 +112,7 @@ namespace YooAsset
}
internal override void InternalWaitForAsyncComplete()
{
//TODO 场景加载不支持异步转同步,为了支持同步加载方法需要实现该方法!
//注意:场景加载不支持异步转同步,为了支持同步加载方法需要实现该方法!
InternalUpdate();
}
public override void UnSuspendLoad()

View File

@@ -7,6 +7,114 @@ namespace YooAsset
{
internal static class CatalogTools
{
#if UNITY_EDITOR
/// <summary>
/// 生成包裹的内置资源目录文件
/// 说明:根据指定目录下的文件生成清单文件。
/// </summary>
public static bool CreateCatalogFile(IManifestRestoreServices services, string packageName, string packageDirectory)
{
// 获取资源清单版本
string packageVersion;
{
string versionFileName = YooAssetSettingsData.GetPackageVersionFileName(packageName);
string versionFilePath = $"{packageDirectory}/{versionFileName}";
if (File.Exists(versionFilePath) == false)
{
Debug.LogError($"Can not found package version file : {versionFilePath}");
return false;
}
packageVersion = FileUtility.ReadAllText(versionFilePath);
}
// 加载资源清单文件
PackageManifest packageManifest;
{
string manifestFileName = YooAssetSettingsData.GetManifestBinaryFileName(packageName, packageVersion);
string manifestFilePath = $"{packageDirectory}/{manifestFileName}";
if (File.Exists(manifestFilePath) == false)
{
Debug.LogError($"Can not found package manifest file : {manifestFilePath}");
return false;
}
var binaryData = FileUtility.ReadAllBytes(manifestFilePath);
packageManifest = ManifestTools.DeserializeFromBinary(binaryData, services);
}
// 获取文件名映射关系
Dictionary<string, string> fileMapping = new Dictionary<string, string>();
{
foreach (var packageBundle in packageManifest.BundleList)
{
fileMapping.Add(packageBundle.FileName, packageBundle.BundleGUID);
}
}
// 创建内置清单实例
var buildinFileCatalog = new DefaultBuildinFileCatalog();
buildinFileCatalog.FileVersion = CatalogDefine.FileVersion;
buildinFileCatalog.PackageName = packageName;
buildinFileCatalog.PackageVersion = packageVersion;
// 创建白名单查询集合
HashSet<string> whiteFileList = new HashSet<string>
{
"link.xml",
"buildlogtep.json",
$"{packageName}.version",
$"{packageName}_{packageVersion}.bytes",
$"{packageName}_{packageVersion}.hash",
$"{packageName}_{packageVersion}.json",
$"{packageName}_{packageVersion}.report",
DefaultBuildinFileSystemDefine.BuildinCatalogJsonFileName,
DefaultBuildinFileSystemDefine.BuildinCatalogBinaryFileName
};
// 记录所有内置资源文件
DirectoryInfo rootDirectory = new DirectoryInfo(packageDirectory);
FileInfo[] fileInfos = rootDirectory.GetFiles();
foreach (var fileInfo in fileInfos)
{
if (fileInfo.Extension == ".meta")
continue;
if (whiteFileList.Contains(fileInfo.Name))
continue;
string fileName = fileInfo.Name;
if (fileMapping.TryGetValue(fileName, out string bundleGUID))
{
var wrapper = new DefaultBuildinFileCatalog.FileWrapper();
wrapper.BundleGUID = bundleGUID;
wrapper.FileName = fileName;
buildinFileCatalog.Wrappers.Add(wrapper);
}
else
{
Debug.LogWarning($"Failed mapping file : {fileName}");
}
}
// 创建输出文件
string jsonFilePath = $"{packageDirectory}/{DefaultBuildinFileSystemDefine.BuildinCatalogJsonFileName}";
if (File.Exists(jsonFilePath))
File.Delete(jsonFilePath);
SerializeToJson(jsonFilePath, buildinFileCatalog);
// 创建输出文件
string binaryFilePath = $"{packageDirectory}/{DefaultBuildinFileSystemDefine.BuildinCatalogBinaryFileName}";
if (File.Exists(binaryFilePath))
File.Delete(binaryFilePath);
SerializeToBinary(binaryFilePath, buildinFileCatalog);
UnityEditor.AssetDatabase.Refresh();
Debug.Log($"Succeed to save catalog file : {binaryFilePath}");
return true;
}
#endif
/// <summary>
/// 序列化JSON文件
/// </summary>

View File

@@ -53,15 +53,20 @@ namespace YooAsset
}
#region
/// <summary>
/// 自定义参数:覆盖安装缓存清理模式
/// </summary>
public EOverwriteInstallClearMode InstallClearMode { private set; get; } = EOverwriteInstallClearMode.ClearAllManifestFiles;
/// <summary>
/// 自定义参数:初始化的时候缓存文件校验级别
/// </summary>
public EFileVerifyLevel FileVerifyLevel { private set; get; } = EFileVerifyLevel.Middle;
/// <summary>
/// 自定义参数:覆盖安装缓存清理模式
/// 自定义参数:初始化的时候缓存文件校验最大并发数
/// </summary>
public EOverwriteInstallClearMode InstallClearMode { private set; get; } = EOverwriteInstallClearMode.ClearAllManifestFiles;
public int FileVerifyMaxConcurrency { private set; get; } = int.MaxValue;
/// <summary>
/// 自定义参数:数据文件追加文件格式
@@ -88,6 +93,16 @@ namespace YooAsset
/// 自定义参数:解密方法类
/// </summary>
public IDecryptionServices DecryptionServices { private set; get; }
/// <summary>
/// 自定义参数:资源清单服务类
/// </summary>
public IManifestRestoreServices ManifestServices { private set; get; }
/// <summary>
/// 自定义参数:拷贝内置文件服务类
/// </summary>
public ICopyLocalFileServices CopyLocalFileServices { private set; get; }
#endregion
@@ -115,7 +130,7 @@ namespace YooAsset
}
public virtual FSDownloadFileOperation DownloadFileAsync(PackageBundle bundle, DownloadFileOptions options)
{
// 注意:业务层的解压下载器会依赖内置文件系统的下载方法
// 注意:业务层的解压器会依赖方法
options.ImportFilePath = GetBuildinFileLoadPath(bundle);
return _unpackFileSystem.DownloadFileAsync(bundle, options);
}
@@ -146,13 +161,18 @@ namespace YooAsset
public virtual void SetParameter(string name, object value)
{
if (name == FileSystemParametersDefine.FILE_VERIFY_LEVEL)
if (name == FileSystemParametersDefine.INSTALL_CLEAR_MODE)
{
InstallClearMode = (EOverwriteInstallClearMode)value;
}
else if (name == FileSystemParametersDefine.FILE_VERIFY_LEVEL)
{
FileVerifyLevel = (EFileVerifyLevel)value;
}
else if (name == FileSystemParametersDefine.INSTALL_CLEAR_MODE)
else if (name == FileSystemParametersDefine.FILE_VERIFY_MAX_CONCURRENCY)
{
InstallClearMode = (EOverwriteInstallClearMode)value;
int convertValue = Convert.ToInt32(value);
FileVerifyMaxConcurrency = Mathf.Clamp(convertValue, 1, int.MaxValue);
}
else if (name == FileSystemParametersDefine.APPEND_FILE_EXTENSION)
{
@@ -174,6 +194,14 @@ namespace YooAsset
{
DecryptionServices = (IDecryptionServices)value;
}
else if (name == FileSystemParametersDefine.MANIFEST_SERVICES)
{
ManifestServices = (IManifestRestoreServices)value;
}
else if (name == FileSystemParametersDefine.COPY_LOCAL_FILE_SERVICES)
{
CopyLocalFileServices = (ICopyLocalFileServices)value;
}
else
{
YooLogger.Warning($"Invalid parameter : {name}");
@@ -192,10 +220,12 @@ namespace YooAsset
var remoteServices = new DefaultUnpackRemoteServices(_packageRoot);
_unpackFileSystem = new DefaultUnpackFileSystem();
_unpackFileSystem.SetParameter(FileSystemParametersDefine.REMOTE_SERVICES, remoteServices);
_unpackFileSystem.SetParameter(FileSystemParametersDefine.FILE_VERIFY_LEVEL, FileVerifyLevel);
_unpackFileSystem.SetParameter(FileSystemParametersDefine.INSTALL_CLEAR_MODE, InstallClearMode);
_unpackFileSystem.SetParameter(FileSystemParametersDefine.FILE_VERIFY_LEVEL, FileVerifyLevel);
_unpackFileSystem.SetParameter(FileSystemParametersDefine.FILE_VERIFY_MAX_CONCURRENCY, FileVerifyMaxConcurrency);
_unpackFileSystem.SetParameter(FileSystemParametersDefine.APPEND_FILE_EXTENSION, AppendFileExtension);
_unpackFileSystem.SetParameter(FileSystemParametersDefine.DECRYPTION_SERVICES, DecryptionServices);
_unpackFileSystem.SetParameter(FileSystemParametersDefine.COPY_LOCAL_FILE_SERVICES, CopyLocalFileServices);
_unpackFileSystem.OnCreate(packageName, null);
}
public virtual void OnDestroy()
@@ -316,6 +346,27 @@ namespace YooAsset
#endif
}
/// <summary>
/// 是否属于解压资源包文件
/// </summary>
protected virtual bool IsUnpackBundleFile(PackageBundle bundle)
{
if (Belong(bundle) == false)
return false;
#if UNITY_ANDROID || UNITY_OPENHARMONY
if (bundle.Encrypted)
return true;
if (bundle.BundleType == (int)EBuildBundleType.RawBundle)
return true;
return false;
#else
return false;
#endif
}
#region
protected string GetDefaultBuildinPackageRoot(string packageName)
{
@@ -351,27 +402,6 @@ namespace YooAsset
return PathUtility.Combine(_packageRoot, DefaultBuildinFileSystemDefine.BuildinCatalogBinaryFileName);
}
/// <summary>
/// 是否属于解压资源包文件
/// </summary>
protected bool IsUnpackBundleFile(PackageBundle bundle)
{
if (Belong(bundle) == false)
return false;
#if UNITY_ANDROID
if (bundle.Encrypted)
return true;
if (bundle.BundleType == (int)EBuildBundleType.RawBundle)
return true;
return false;
#else
return false;
#endif
}
/// <summary>
/// 记录文件信息
/// </summary>

View File

@@ -1,148 +0,0 @@
#if UNITY_EDITOR
using System.Collections.Generic;
using System.IO;
using UnityEngine;
namespace YooAsset
{
public class DefaultBuildinFileSystemBuild : UnityEditor.Build.IPreprocessBuildWithReport
{
public int callbackOrder { get { return 0; } }
/// <summary>
/// 在构建应用程序前自动生成内置资源目录文件。
/// 原理搜索StreamingAssets目录下的所有资源文件然后将这些文件信息写入文件并存储在Resources目录下。
/// </summary>
public void OnPreprocessBuild(UnityEditor.Build.Reporting.BuildReport report)
{
YooLogger.Log("Begin to create catalog file !");
string rootPath = YooAssetSettingsData.GetYooDefaultBuildinRoot();
DirectoryInfo rootDirectory = new DirectoryInfo(rootPath);
if (rootDirectory.Exists == false)
{
UnityEngine.Debug.LogWarning($"Can not found StreamingAssets root directory : {rootPath}");
return;
}
// 搜索所有Package目录
DirectoryInfo[] subDirectories = rootDirectory.GetDirectories();
foreach (var subDirectory in subDirectories)
{
string packageName = subDirectory.Name;
string pacakgeDirectory = subDirectory.FullName;
bool result = CreateBuildinCatalogFile(packageName, pacakgeDirectory);
if (result == false)
{
throw new System.Exception($"Create package {packageName} catalog file failed ! See the detail error in console !");
}
}
}
/// <summary>
/// 生成包裹的内置资源目录文件
/// </summary>
public static bool CreateBuildinCatalogFile(string packageName, string pacakgeDirectory)
{
// 获取资源清单版本
string packageVersion;
{
string versionFileName = YooAssetSettingsData.GetPackageVersionFileName(packageName);
string versionFilePath = $"{pacakgeDirectory}/{versionFileName}";
if (File.Exists(versionFilePath) == false)
{
Debug.LogError($"Can not found package version file : {versionFilePath}");
return false;
}
packageVersion = FileUtility.ReadAllText(versionFilePath);
}
// 加载资源清单文件
PackageManifest packageManifest;
{
string manifestFileName = YooAssetSettingsData.GetManifestBinaryFileName(packageName, packageVersion);
string manifestFilePath = $"{pacakgeDirectory}/{manifestFileName}";
if (File.Exists(manifestFilePath) == false)
{
Debug.LogError($"Can not found package manifest file : {manifestFilePath}");
return false;
}
var binaryData = FileUtility.ReadAllBytes(manifestFilePath);
packageManifest = ManifestTools.DeserializeFromBinary(binaryData);
}
// 获取文件名映射关系
Dictionary<string, string> fileMapping = new Dictionary<string, string>();
{
foreach (var packageBundle in packageManifest.BundleList)
{
fileMapping.Add(packageBundle.FileName, packageBundle.BundleGUID);
}
}
// 创建内置清单实例
var buildinFileCatalog = new DefaultBuildinFileCatalog();
buildinFileCatalog.FileVersion = CatalogDefine.FileVersion;
buildinFileCatalog.PackageName = packageName;
buildinFileCatalog.PackageVersion = packageVersion;
// 创建白名单查询集合
HashSet<string> whiteFileList = new HashSet<string>
{
"link.xml",
"buildlogtep.json",
$"{packageName}.version",
$"{packageName}_{packageVersion}.bytes",
$"{packageName}_{packageVersion}.hash",
$"{packageName}_{packageVersion}.json",
$"{packageName}_{packageVersion}.report",
DefaultBuildinFileSystemDefine.BuildinCatalogJsonFileName,
DefaultBuildinFileSystemDefine.BuildinCatalogBinaryFileName
};
// 记录所有内置资源文件
DirectoryInfo rootDirectory = new DirectoryInfo(pacakgeDirectory);
FileInfo[] fileInfos = rootDirectory.GetFiles();
foreach (var fileInfo in fileInfos)
{
if (fileInfo.Extension == ".meta")
continue;
if (whiteFileList.Contains(fileInfo.Name))
continue;
string fileName = fileInfo.Name;
if (fileMapping.TryGetValue(fileName, out string bundleGUID))
{
var wrapper = new DefaultBuildinFileCatalog.FileWrapper();
wrapper.BundleGUID = bundleGUID;
wrapper.FileName = fileName;
buildinFileCatalog.Wrappers.Add(wrapper);
}
else
{
Debug.LogWarning($"Failed mapping file : {fileName}");
}
}
// 创建输出文件
string jsonFilePath = $"{pacakgeDirectory}/{DefaultBuildinFileSystemDefine.BuildinCatalogJsonFileName}";
if (File.Exists(jsonFilePath))
File.Delete(jsonFilePath);
CatalogTools.SerializeToJson(jsonFilePath, buildinFileCatalog);
// 创建输出文件
string binaryFilePath = $"{pacakgeDirectory}/{DefaultBuildinFileSystemDefine.BuildinCatalogBinaryFileName}";
if (File.Exists(binaryFilePath))
File.Delete(binaryFilePath);
CatalogTools.SerializeToBinary(binaryFilePath, buildinFileCatalog);
UnityEditor.AssetDatabase.Refresh();
Debug.Log($"Succeed to save buildin file catalog : {binaryFilePath}");
return true;
}
}
}
#endif

View File

@@ -8,16 +8,20 @@ namespace YooAsset
private enum ESteps
{
None,
CopyBuildinManifest,
LoadBuildinPackageVersion,
CopyBuildinPackageHash,
CopyBuildinPackageManifest,
InitUnpackFileSystem,
LoadCatalogFile,
Done,
}
private readonly DefaultBuildinFileSystem _fileSystem;
private CopyBuildinPackageManifestOperation _copyBuildinPackageManifestOp;
private RequestBuildinPackageVersionOperation _requestBuildinPackageVersionOp;
private CopyBuildinFileOperation _copyBuildinHashFileOp;
private CopyBuildinFileOperation _copyBuildinManifestFileOp;
private FSInitializeFileSystemOperation _initUnpackFIleSystemOp;
private LoadBuildinCatalogFileOperation _loadCatalogFileOp;
private LoadBuildinCatalogFileOperation _loadBuildinCatalogFileOp;
private ESteps _steps = ESteps.None;
internal DBFSInitializeOperation(DefaultBuildinFileSystem fileSystem)
@@ -32,7 +36,7 @@ namespace YooAsset
Error = $"{nameof(DefaultBuildinFileSystem)} is not support WEBGL platform !";
#else
if (_fileSystem.CopyBuildinPackageManifest)
_steps = ESteps.CopyBuildinManifest;
_steps = ESteps.LoadBuildinPackageVersion;
else
_steps = ESteps.InitUnpackFileSystem;
#endif
@@ -42,20 +46,76 @@ namespace YooAsset
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.CopyBuildinManifest)
if (_steps == ESteps.LoadBuildinPackageVersion)
{
if (_copyBuildinPackageManifestOp == null)
if (_requestBuildinPackageVersionOp == null)
{
_copyBuildinPackageManifestOp = new CopyBuildinPackageManifestOperation(_fileSystem);
_copyBuildinPackageManifestOp.StartOperation();
AddChildOperation(_copyBuildinPackageManifestOp);
_requestBuildinPackageVersionOp = new RequestBuildinPackageVersionOperation(_fileSystem);
_requestBuildinPackageVersionOp.StartOperation();
AddChildOperation(_requestBuildinPackageVersionOp);
}
_copyBuildinPackageManifestOp.UpdateOperation();
if (_copyBuildinPackageManifestOp.IsDone == false)
_requestBuildinPackageVersionOp.UpdateOperation();
if (_requestBuildinPackageVersionOp.IsDone == false)
return;
if (_copyBuildinPackageManifestOp.Status == EOperationStatus.Succeed)
if (_requestBuildinPackageVersionOp.Status == EOperationStatus.Succeed)
{
_steps = ESteps.CopyBuildinPackageHash;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _requestBuildinPackageVersionOp.Error;
}
}
if (_steps == ESteps.CopyBuildinPackageHash)
{
if (_copyBuildinHashFileOp == null)
{
string packageVersion = _requestBuildinPackageVersionOp.PackageVersion;
string destFilePath = GetCopyPackageHashDestPath(packageVersion);
string sourceFilePath = _fileSystem.GetBuildinPackageHashFilePath(packageVersion);
_copyBuildinHashFileOp = new CopyBuildinFileOperation(sourceFilePath, destFilePath);
_copyBuildinHashFileOp.StartOperation();
AddChildOperation(_copyBuildinHashFileOp);
}
_copyBuildinHashFileOp.UpdateOperation();
if (_copyBuildinHashFileOp.IsDone == false)
return;
if (_copyBuildinHashFileOp.Status == EOperationStatus.Succeed)
{
_steps = ESteps.CopyBuildinPackageManifest;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _copyBuildinHashFileOp.Error;
}
}
if (_steps == ESteps.CopyBuildinPackageManifest)
{
if (_copyBuildinManifestFileOp == null)
{
string packageVersion = _requestBuildinPackageVersionOp.PackageVersion;
string destFilePath = GetCopyPackageManifestDestPath(packageVersion);
string sourceFilePath = _fileSystem.GetBuildinPackageManifestFilePath(packageVersion);
_copyBuildinManifestFileOp = new CopyBuildinFileOperation(sourceFilePath, destFilePath);
_copyBuildinManifestFileOp.StartOperation();
AddChildOperation(_copyBuildinManifestFileOp);
}
_copyBuildinManifestFileOp.UpdateOperation();
if (_copyBuildinManifestFileOp.IsDone == false)
return;
if (_copyBuildinManifestFileOp.Status == EOperationStatus.Succeed)
{
_steps = ESteps.InitUnpackFileSystem;
}
@@ -63,7 +123,7 @@ namespace YooAsset
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _copyBuildinPackageManifestOp.Error;
Error = _copyBuildinManifestFileOp.Error;
}
}
@@ -103,33 +163,43 @@ namespace YooAsset
if (_steps == ESteps.LoadCatalogFile)
{
if (_loadCatalogFileOp == null)
if (_loadBuildinCatalogFileOp == null)
{
#if UNITY_EDITOR
// 兼容性初始化
// 说明:内置文件系统在编辑器下运行时需要动态生成
string packageRoot = _fileSystem.FileRoot;
bool result = DefaultBuildinFileSystemBuild.CreateBuildinCatalogFile(_fileSystem.PackageName, packageRoot);
if (result == false)
_loadBuildinCatalogFileOp = new LoadBuildinCatalogFileOperation(_fileSystem);
_loadBuildinCatalogFileOp.StartOperation();
AddChildOperation(_loadBuildinCatalogFileOp);
}
_loadBuildinCatalogFileOp.UpdateOperation();
if (_loadBuildinCatalogFileOp.IsDone == false)
return;
if (_loadBuildinCatalogFileOp.Status == EOperationStatus.Succeed)
{
var catalog = _loadBuildinCatalogFileOp.Catalog;
if (catalog == null)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Create package catalog file failed ! See the detail error in console !";
Error = "Fatal error : catalog is null !";
return;
}
#endif
_loadCatalogFileOp = new LoadBuildinCatalogFileOperation(_fileSystem);
_loadCatalogFileOp.StartOperation();
AddChildOperation(_loadCatalogFileOp);
}
if (catalog.PackageName != _fileSystem.PackageName)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Catalog file package name {catalog.PackageName} cannot match the file system package name {_fileSystem.PackageName}";
return;
}
_loadCatalogFileOp.UpdateOperation();
if (_loadCatalogFileOp.IsDone == false)
return;
foreach (var wrapper in catalog.Wrappers)
{
var fileWrapper = new DefaultBuildinFileSystem.FileWrapper(wrapper.FileName);
_fileSystem.RecordCatalogFile(wrapper.BundleGUID, fileWrapper);
}
if (_loadCatalogFileOp.Status == EOperationStatus.Succeed)
{
YooLogger.Log($"Package '{_fileSystem.PackageName}' buildin catalog files count : {catalog.Wrappers.Count}");
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
@@ -137,9 +207,32 @@ namespace YooAsset
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _loadCatalogFileOp.Error;
Error = _loadBuildinCatalogFileOp.Error;
}
}
}
private string GetCopyManifestFileRoot()
{
string destRoot = _fileSystem.CopyBuildinPackageManifestDestRoot;
if (string.IsNullOrEmpty(destRoot))
{
string defaultCacheRoot = YooAssetSettingsData.GetYooDefaultCacheRoot();
destRoot = PathUtility.Combine(defaultCacheRoot, _fileSystem.PackageName, DefaultCacheFileSystemDefine.ManifestFilesFolderName);
}
return destRoot;
}
private string GetCopyPackageHashDestPath(string packageVersion)
{
string fileRoot = GetCopyManifestFileRoot();
string fileName = YooAssetSettingsData.GetPackageHashFileName(_fileSystem.PackageName, packageVersion);
return PathUtility.Combine(fileRoot, fileName);
}
private string GetCopyPackageManifestDestPath(string packageVersion)
{
string fileRoot = GetCopyManifestFileRoot();
string fileName = YooAssetSettingsData.GetManifestBinaryFileName(_fileSystem.PackageName, packageVersion);
return PathUtility.Combine(fileRoot, fileName);
}
}
}

View File

@@ -104,27 +104,28 @@ namespace YooAsset
}
}
if (_assetBundle != null)
if (_assetBundle == null)
{
_steps = ESteps.Done;
Result = new AssetBundleResult(_fileSystem, _bundle, _assetBundle, _managedStream);
Status = EOperationStatus.Succeed;
return;
}
if (_bundle.Encrypted)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Failed to load encrypted buildin asset bundle file : {_bundle.BundleName}";
YooLogger.Error(Error);
if (_bundle.Encrypted)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Failed to load encrypted buildin asset bundle file : {_bundle.BundleName}";
YooLogger.Error(Error);
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Failed to load buildin asset bundle file : {_bundle.BundleName}";
YooLogger.Error(Error);
}
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Failed to load buildin asset bundle file : {_bundle.BundleName}";
YooLogger.Error(Error);
Result = new AssetBundleResult(_fileSystem, _bundle, _assetBundle, _managedStream);
Status = EOperationStatus.Succeed;
}
}
}
@@ -176,13 +177,15 @@ namespace YooAsset
if (_steps == ESteps.LoadBuildinRawBundle)
{
string filePath = _fileSystem.GetBuildinFileLoadPath(_bundle);
#if UNITY_ANDROID
//TODO : 安卓平台内置文件属于APK压缩包内的文件。
_steps = ESteps.Done;
Result = new RawBundleResult(_fileSystem, _bundle);
Status = EOperationStatus.Succeed;
Status = EOperationStatus.Failed;
Error = $"Can not load android buildin raw bundle file : {filePath}";
YooLogger.Error(Error);
#else
string filePath = _fileSystem.GetBuildinFileLoadPath(_bundle);
if (File.Exists(filePath))
{
_steps = ESteps.Done;

View File

@@ -0,0 +1,102 @@
using System;
using System.IO;
namespace YooAsset
{
internal class CopyBuildinFileOperation : AsyncOperationBase
{
private enum ESteps
{
None,
CheckFileExist,
TryCopyFile,
UnpackFile,
Done,
}
private UnityWebFileRequestOperation _webFileRequestOp;
private readonly string _sourceFilePath;
private readonly string _destFilePath;
private ESteps _steps = ESteps.None;
public CopyBuildinFileOperation(string sourceFilePath, string destFilePath)
{
_sourceFilePath = sourceFilePath;
_destFilePath = destFilePath;
}
internal override void InternalStart()
{
_steps = ESteps.CheckFileExist;
}
internal override void InternalUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.CheckFileExist)
{
if (File.Exists(_destFilePath))
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
else
{
_steps = ESteps.TryCopyFile;
}
}
if (_steps == ESteps.TryCopyFile)
{
if (File.Exists(_sourceFilePath))
{
try
{
var directory = Path.GetDirectoryName(_destFilePath);
if (Directory.Exists(directory) == false)
Directory.CreateDirectory(directory);
File.Copy(_sourceFilePath, _destFilePath, true);
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
catch (Exception ex)
{
YooLogger.Warning($"Failed copy buildin file : {ex.Message}");
_steps = ESteps.UnpackFile;
}
}
else
{
_steps = ESteps.UnpackFile;
}
}
if (_steps == ESteps.UnpackFile)
{
if (_webFileRequestOp == null)
{
string url = DownloadSystemHelper.ConvertToWWWPath(_sourceFilePath);
_webFileRequestOp = new UnityWebFileRequestOperation(url, _destFilePath, 60);
_webFileRequestOp.StartOperation();
AddChildOperation(_webFileRequestOp);
}
_webFileRequestOp.UpdateOperation();
if (_webFileRequestOp.IsDone == false)
return;
if (_webFileRequestOp.Status == EOperationStatus.Succeed)
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _webFileRequestOp.Error;
}
}
}
}
}

View File

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

View File

@@ -1,173 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
namespace YooAsset
{
internal class CopyBuildinPackageManifestOperation : AsyncOperationBase
{
private enum ESteps
{
None,
RequestPackageVersion,
CheckHashFile,
UnpackHashFile,
CheckManifestFile,
UnpackManifestFile,
Done,
}
private readonly DefaultBuildinFileSystem _fileSystem;
private RequestBuildinPackageVersionOperation _requestBuildinPackageVersionOp;
private UnityWebFileRequestOperation _hashFileRequestOp;
private UnityWebFileRequestOperation _manifestFileRequestOp;
private string _buildinPackageVersion;
private ESteps _steps = ESteps.None;
public CopyBuildinPackageManifestOperation(DefaultBuildinFileSystem fileSystem)
{
_fileSystem = fileSystem;
}
internal override void InternalStart()
{
_steps = ESteps.RequestPackageVersion;
}
internal override void InternalUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.RequestPackageVersion)
{
if (_requestBuildinPackageVersionOp == null)
{
_requestBuildinPackageVersionOp = new RequestBuildinPackageVersionOperation(_fileSystem);
_requestBuildinPackageVersionOp.StartOperation();
AddChildOperation(_requestBuildinPackageVersionOp);
}
_requestBuildinPackageVersionOp.UpdateOperation();
if (_requestBuildinPackageVersionOp.IsDone == false)
return;
if (_requestBuildinPackageVersionOp.Status == EOperationStatus.Succeed)
{
_steps = ESteps.CheckHashFile;
_buildinPackageVersion = _requestBuildinPackageVersionOp.PackageVersion;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _requestBuildinPackageVersionOp.Error;
}
}
if (_steps == ESteps.CheckHashFile)
{
string hashFilePath = GetCopyPackageHashDestPath(_buildinPackageVersion);
if (File.Exists(hashFilePath))
{
_steps = ESteps.CheckManifestFile;
return;
}
_steps = ESteps.UnpackHashFile;
}
if (_steps == ESteps.UnpackHashFile)
{
if (_hashFileRequestOp == null)
{
string sourcePath = _fileSystem.GetBuildinPackageHashFilePath(_buildinPackageVersion);
string destPath = GetCopyPackageHashDestPath(_buildinPackageVersion);
string url = DownloadSystemHelper.ConvertToWWWPath(sourcePath);
_hashFileRequestOp = new UnityWebFileRequestOperation(url, destPath);
_hashFileRequestOp.StartOperation();
AddChildOperation(_hashFileRequestOp);
}
_hashFileRequestOp.UpdateOperation();
if (_hashFileRequestOp.IsDone == false)
return;
if (_hashFileRequestOp.Status == EOperationStatus.Succeed)
{
_steps = ESteps.CheckManifestFile;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _hashFileRequestOp.Error;
}
}
if (_steps == ESteps.CheckManifestFile)
{
string manifestFilePath = GetCopyPackageManifestDestPath(_buildinPackageVersion);
if (File.Exists(manifestFilePath))
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
return;
}
_steps = ESteps.UnpackManifestFile;
}
if (_steps == ESteps.UnpackManifestFile)
{
if (_manifestFileRequestOp == null)
{
string sourcePath = _fileSystem.GetBuildinPackageManifestFilePath(_buildinPackageVersion);
string destPath = GetCopyPackageManifestDestPath(_buildinPackageVersion);
string url = DownloadSystemHelper.ConvertToWWWPath(sourcePath);
_manifestFileRequestOp = new UnityWebFileRequestOperation(url, destPath);
_manifestFileRequestOp.StartOperation();
AddChildOperation(_manifestFileRequestOp);
}
_manifestFileRequestOp.UpdateOperation();
if (_manifestFileRequestOp.IsDone == false)
return;
if (_manifestFileRequestOp.Status == EOperationStatus.Succeed)
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _manifestFileRequestOp.Error;
}
}
}
private string GetCopyManifestFileRoot()
{
string destRoot = _fileSystem.CopyBuildinPackageManifestDestRoot;
if (string.IsNullOrEmpty(destRoot))
{
string defaultCacheRoot = YooAssetSettingsData.GetYooDefaultCacheRoot();
destRoot = PathUtility.Combine(defaultCacheRoot, _fileSystem.PackageName, DefaultCacheFileSystemDefine.ManifestFilesFolderName);
}
return destRoot;
}
private string GetCopyPackageHashDestPath(string packageVersion)
{
string fileRoot = GetCopyManifestFileRoot();
string fileName = YooAssetSettingsData.GetPackageHashFileName(_fileSystem.PackageName, packageVersion);
return PathUtility.Combine(fileRoot, fileName);
}
private string GetCopyPackageManifestDestPath(string packageVersion)
{
string fileRoot = GetCopyManifestFileRoot();
string fileName = YooAssetSettingsData.GetManifestBinaryFileName(_fileSystem.PackageName, packageVersion);
return PathUtility.Combine(fileRoot, fileName);
}
}
}

View File

@@ -1,4 +1,5 @@
using System;
using System.IO;
namespace YooAsset
{
@@ -7,35 +8,56 @@ namespace YooAsset
private enum ESteps
{
None,
RequestData,
TryLoadFileData,
RequestFileData,
LoadCatalog,
Done,
}
private readonly DefaultBuildinFileSystem _fileSystem;
private UnityWebDataRequestOperation _webDataRequestOp;
private byte[] _fileData;
private ESteps _steps = ESteps.None;
/// <summary>
/// 内置资源目录
/// </summary>
public DefaultBuildinFileCatalog Catalog;
internal LoadBuildinCatalogFileOperation(DefaultBuildinFileSystem fileSystem)
{
_fileSystem = fileSystem;
}
internal override void InternalStart()
{
_steps = ESteps.RequestData;
_steps = ESteps.TryLoadFileData;
}
internal override void InternalUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.RequestData)
if (_steps == ESteps.TryLoadFileData)
{
string filePath = _fileSystem.GetCatalogBinaryFileLoadPath();
if (File.Exists(filePath))
{
_fileData = File.ReadAllBytes(filePath);
_steps = ESteps.LoadCatalog;
}
else
{
_steps = ESteps.RequestFileData;
}
}
if (_steps == ESteps.RequestFileData)
{
if (_webDataRequestOp == null)
{
string filePath = _fileSystem.GetCatalogBinaryFileLoadPath();
string url = DownloadSystemHelper.ConvertToWWWPath(filePath);
_webDataRequestOp = new UnityWebDataRequestOperation(url);
_webDataRequestOp = new UnityWebDataRequestOperation(url, 60);
_webDataRequestOp.StartOperation();
AddChildOperation(_webDataRequestOp);
}
@@ -46,6 +68,7 @@ namespace YooAsset
if (_webDataRequestOp.Status == EOperationStatus.Succeed)
{
_fileData = _webDataRequestOp.Result;
_steps = ESteps.LoadCatalog;
}
else
@@ -60,22 +83,7 @@ namespace YooAsset
{
try
{
var catalog = CatalogTools.DeserializeFromBinary(_webDataRequestOp.Result);
if (catalog.PackageName != _fileSystem.PackageName)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Catalog file package name {catalog.PackageName} cannot match the file system package name {_fileSystem.PackageName}";
return;
}
foreach (var wrapper in catalog.Wrappers)
{
var fileWrapper = new DefaultBuildinFileSystem.FileWrapper(wrapper.FileName);
_fileSystem.RecordCatalogFile(wrapper.BundleGUID, fileWrapper);
}
YooLogger.Log($"Package '{_fileSystem.PackageName}' buildin catalog files count : {catalog.Wrappers.Count}");
Catalog = CatalogTools.DeserializeFromBinary(_fileData);
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}

View File

@@ -1,4 +1,5 @@

using System.IO;
namespace YooAsset
{
internal class LoadBuildinPackageManifestOperation : AsyncOperationBase
@@ -6,6 +7,7 @@ namespace YooAsset
private enum ESteps
{
None,
TryLoadFileData,
RequestFileData,
VerifyFileData,
LoadManifest,
@@ -17,6 +19,7 @@ namespace YooAsset
private readonly string _packageHash;
private UnityWebDataRequestOperation _webDataRequestOp;
private DeserializeManifestOperation _deserializer;
private byte[] _fileData;
private ESteps _steps = ESteps.None;
/// <summary>
@@ -33,20 +36,34 @@ namespace YooAsset
}
internal override void InternalStart()
{
_steps = ESteps.RequestFileData;
_steps = ESteps.TryLoadFileData;
}
internal override void InternalUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.TryLoadFileData)
{
string filePath = _fileSystem.GetBuildinPackageManifestFilePath(_packageVersion);
if (File.Exists(filePath))
{
_fileData = File.ReadAllBytes(filePath);
_steps = ESteps.VerifyFileData;
}
else
{
_steps = ESteps.RequestFileData;
}
}
if (_steps == ESteps.RequestFileData)
{
if (_webDataRequestOp == null)
{
string filePath = _fileSystem.GetBuildinPackageManifestFilePath(_packageVersion);
string url = DownloadSystemHelper.ConvertToWWWPath(filePath);
_webDataRequestOp = new UnityWebDataRequestOperation(url);
_webDataRequestOp = new UnityWebDataRequestOperation(url, 60);
_webDataRequestOp.StartOperation();
AddChildOperation(_webDataRequestOp);
}
@@ -57,6 +74,7 @@ namespace YooAsset
if (_webDataRequestOp.Status == EOperationStatus.Succeed)
{
_fileData = _webDataRequestOp.Result;
_steps = ESteps.VerifyFileData;
}
else
@@ -69,7 +87,7 @@ namespace YooAsset
if (_steps == ESteps.VerifyFileData)
{
if (ManifestTools.VerifyManifestData(_webDataRequestOp.Result, _packageHash))
if (ManifestTools.VerifyManifestData(_fileData, _packageHash))
{
_steps = ESteps.LoadManifest;
}
@@ -85,7 +103,7 @@ namespace YooAsset
{
if (_deserializer == null)
{
_deserializer = new DeserializeManifestOperation(_webDataRequestOp.Result);
_deserializer = new DeserializeManifestOperation(_fileSystem.ManifestServices, _fileData);
_deserializer.StartOperation();
AddChildOperation(_deserializer);
}

View File

@@ -1,4 +1,5 @@

using System.IO;
namespace YooAsset
{
internal class RequestBuildinPackageHashOperation : AsyncOperationBase
@@ -6,7 +7,9 @@ namespace YooAsset
private enum ESteps
{
None,
TryLoadPackageHash,
RequestPackageHash,
CheckResult,
Done,
}
@@ -28,20 +31,34 @@ namespace YooAsset
}
internal override void InternalStart()
{
_steps = ESteps.RequestPackageHash;
_steps = ESteps.TryLoadPackageHash;
}
internal override void InternalUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.TryLoadPackageHash)
{
string filePath = _fileSystem.GetBuildinPackageHashFilePath(_packageVersion);
if (File.Exists(filePath))
{
PackageHash = File.ReadAllText(filePath);
_steps = ESteps.CheckResult;
}
else
{
_steps = ESteps.RequestPackageHash;
}
}
if (_steps == ESteps.RequestPackageHash)
{
if (_webTextRequestOp == null)
{
string filePath = _fileSystem.GetBuildinPackageHashFilePath(_packageVersion);
string url = DownloadSystemHelper.ConvertToWWWPath(filePath);
_webTextRequestOp = new UnityWebTextRequestOperation(url);
_webTextRequestOp = new UnityWebTextRequestOperation(url, 60);
_webTextRequestOp.StartOperation();
AddChildOperation(_webTextRequestOp);
}
@@ -53,17 +70,7 @@ namespace YooAsset
if (_webTextRequestOp.Status == EOperationStatus.Succeed)
{
PackageHash = _webTextRequestOp.Result;
if (string.IsNullOrEmpty(PackageHash))
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Buildin package hash file content is empty !";
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
_steps = ESteps.CheckResult;
}
else
{
@@ -72,6 +79,21 @@ namespace YooAsset
Error = _webTextRequestOp.Error;
}
}
if (_steps == ESteps.CheckResult)
{
if (string.IsNullOrEmpty(PackageHash))
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Buildin package hash file content is empty !";
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
}
}
}
}

View File

@@ -1,4 +1,5 @@

using System.IO;
namespace YooAsset
{
internal class RequestBuildinPackageVersionOperation : AsyncOperationBase
@@ -6,7 +7,9 @@ namespace YooAsset
private enum ESteps
{
None,
TryLoadPackageVersion,
RequestPackageVersion,
CheckResult,
Done,
}
@@ -26,20 +29,34 @@ namespace YooAsset
}
internal override void InternalStart()
{
_steps = ESteps.RequestPackageVersion;
_steps = ESteps.TryLoadPackageVersion;
}
internal override void InternalUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.TryLoadPackageVersion)
{
string filePath = _fileSystem.GetBuildinPackageVersionFilePath();
if (File.Exists(filePath))
{
PackageVersion = File.ReadAllText(filePath);
_steps = ESteps.CheckResult;
}
else
{
_steps = ESteps.RequestPackageVersion;
}
}
if (_steps == ESteps.RequestPackageVersion)
{
if (_webTextRequestOp == null)
{
string filePath = _fileSystem.GetBuildinPackageVersionFilePath();
string url = DownloadSystemHelper.ConvertToWWWPath(filePath);
_webTextRequestOp = new UnityWebTextRequestOperation(url);
_webTextRequestOp = new UnityWebTextRequestOperation(url, 60);
_webTextRequestOp.StartOperation();
AddChildOperation(_webTextRequestOp);
}
@@ -51,17 +68,7 @@ namespace YooAsset
if (_webTextRequestOp.Status == EOperationStatus.Succeed)
{
PackageVersion = _webTextRequestOp.Result;
if (string.IsNullOrEmpty(PackageVersion))
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Buildin package version file content is empty !";
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
_steps = ESteps.CheckResult;
}
else
{
@@ -70,6 +77,21 @@ namespace YooAsset
Error = _webTextRequestOp.Error;
}
}
if (_steps == ESteps.CheckResult)
{
if (string.IsNullOrEmpty(PackageVersion))
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Buildin package version file content is empty !";
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
}
}
}
}

View File

@@ -2,6 +2,7 @@
using System.IO;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace YooAsset
{
@@ -58,23 +59,33 @@ namespace YooAsset
/// <summary>
/// 自定义参数:远程服务接口
/// </summary>
public IRemoteServices RemoteServices { private set; get; } = null;
/// <summary>
/// 自定义参数:初始化的时候缓存文件校验级别
/// </summary>
public EFileVerifyLevel FileVerifyLevel { private set; get; } = EFileVerifyLevel.Middle;
public IRemoteServices RemoteServices { private set; get; }
/// <summary>
/// 自定义参数:覆盖安装缓存清理模式
/// </summary>
public EOverwriteInstallClearMode InstallClearMode { private set; get; } = EOverwriteInstallClearMode.ClearAllManifestFiles;
/// <summary>
/// 自定义参数:初始化的时候缓存文件校验级别
/// </summary>
public EFileVerifyLevel FileVerifyLevel { private set; get; } = EFileVerifyLevel.Middle;
/// <summary>
/// 自定义参数:初始化的时候缓存文件校验最大并发数
/// </summary>
public int FileVerifyMaxConcurrency { private set; get; } = int.MaxValue;
/// <summary>
/// 自定义参数:数据文件追加文件格式
/// </summary>
public bool AppendFileExtension { private set; get; } = false;
/// <summary>
/// 自定义参数:禁用边玩边下机制
/// </summary>
public bool DisableOnDemandDownload { private set; get; } = false;
/// <summary>
/// 自定义参数:最大并发连接数
/// </summary>
@@ -85,6 +96,11 @@ namespace YooAsset
/// </summary>
public int DownloadMaxRequestPerFrame { private set; get; } = int.MaxValue;
/// <summary>
/// 自定义参数:下载任务的看门狗机制监控时间
/// </summary>
public int DownloadWatchDogTime { private set; get; } = int.MaxValue;
/// <summary>
/// 自定义参数:启用断点续传的最小尺寸
/// </summary>
@@ -99,6 +115,16 @@ namespace YooAsset
/// 自定义参数:解密方法类
/// </summary>
public IDecryptionServices DecryptionServices { private set; get; }
/// <summary>
/// 自定义参数:资源清单服务类
/// </summary>
public IManifestRestoreServices ManifestServices { private set; get; }
/// <summary>
/// 自定义参数:拷贝内置文件服务类
/// </summary>
public ICopyLocalFileServices CopyLocalFileServices { private set; get; }
#endregion
@@ -156,12 +182,23 @@ namespace YooAsset
}
public virtual FSDownloadFileOperation DownloadFileAsync(PackageBundle bundle, DownloadFileOptions options)
{
var downloader = DownloadCenter.DownloadFileAsync(bundle, options);
downloader.Reference(); //增加下载器的引用计数
// 获取下载地址
if (string.IsNullOrEmpty(options.ImportFilePath))
{
// 注意:如果是解压文件系统类,这里会返回本地内置文件的下载路径
string mainURL = RemoteServices.GetRemoteMainURL(bundle.FileName);
string fallbackURL = RemoteServices.GetRemoteFallbackURL(bundle.FileName);
options.SetURL(mainURL, fallbackURL);
}
else
{
// 注意:把本地导入文件路径转换为下载器请求地址
string mainURL = DownloadSystemHelper.ConvertToWWWPath(options.ImportFilePath);
options.SetURL(mainURL, mainURL);
}
// 注意:将下载器进行包裹,可以避免父类任务终止的时候,连带子任务里的下载器也一起被终止!
var wrapper = new DownloadFileWrapper(downloader);
return wrapper;
var downloader = new DownloadPackageBundleOperation(this, bundle, options);
return downloader;
}
public virtual FSLoadBundleOperation LoadBundleFile(PackageBundle bundle)
{
@@ -189,25 +226,41 @@ namespace YooAsset
{
RemoteServices = (IRemoteServices)value;
}
else if (name == FileSystemParametersDefine.INSTALL_CLEAR_MODE)
{
InstallClearMode = (EOverwriteInstallClearMode)value;
}
else if (name == FileSystemParametersDefine.FILE_VERIFY_LEVEL)
{
FileVerifyLevel = (EFileVerifyLevel)value;
}
else if (name == FileSystemParametersDefine.INSTALL_CLEAR_MODE)
else if (name == FileSystemParametersDefine.FILE_VERIFY_MAX_CONCURRENCY)
{
InstallClearMode = (EOverwriteInstallClearMode)value;
int convertValue = Convert.ToInt32(value);
FileVerifyMaxConcurrency = Mathf.Clamp(convertValue, 1, int.MaxValue);
}
else if (name == FileSystemParametersDefine.APPEND_FILE_EXTENSION)
{
AppendFileExtension = Convert.ToBoolean(value);
}
else if (name == FileSystemParametersDefine.DISABLE_ONDEMAND_DOWNLOAD)
{
DisableOnDemandDownload = Convert.ToBoolean(value);
}
else if (name == FileSystemParametersDefine.DOWNLOAD_MAX_CONCURRENCY)
{
DownloadMaxConcurrency = Convert.ToInt32(value);
int convertValue = Convert.ToInt32(value);
DownloadMaxConcurrency = Mathf.Clamp(convertValue, 1, int.MaxValue);
}
else if (name == FileSystemParametersDefine.DOWNLOAD_MAX_REQUEST_PER_FRAME)
{
DownloadMaxRequestPerFrame = Convert.ToInt32(value);
int convertValue = Convert.ToInt32(value);
DownloadMaxRequestPerFrame = Mathf.Clamp(convertValue, 1, int.MaxValue);
}
else if (name == FileSystemParametersDefine.DOWNLOAD_WATCH_DOG_TIME)
{
int convertValue = Convert.ToInt32(value);
DownloadWatchDogTime = Mathf.Clamp(convertValue, 1, int.MaxValue);
}
else if (name == FileSystemParametersDefine.RESUME_DOWNLOAD_MINMUM_SIZE)
{
@@ -221,6 +274,14 @@ namespace YooAsset
{
DecryptionServices = (IDecryptionServices)value;
}
else if (name == FileSystemParametersDefine.MANIFEST_SERVICES)
{
ManifestServices = (IManifestRestoreServices)value;
}
else if (name == FileSystemParametersDefine.COPY_LOCAL_FILE_SERVICES)
{
CopyLocalFileServices = (ICopyLocalFileServices)value;
}
else
{
YooLogger.Warning($"Invalid parameter : {name}");
@@ -455,22 +516,22 @@ namespace YooAsset
}
private readonly BufferWriter _sharedBuffer = new BufferWriter(1024);
public void WriteBundleInfoFile(string filePath, string dataFileCRC, long dataFileSize)
public void WriteBundleInfoFile(string filePath, uint dataFileCRC, long dataFileSize)
{
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read))
{
_sharedBuffer.Clear();
_sharedBuffer.WriteUTF8(dataFileCRC);
_sharedBuffer.WriteUInt32(dataFileCRC);
_sharedBuffer.WriteInt64(dataFileSize);
_sharedBuffer.WriteToStream(fs);
fs.Flush();
}
}
public void ReadBundleInfoFile(string filePath, out string dataFileCRC, out long dataFileSize)
public void ReadBundleInfoFile(string filePath, out uint dataFileCRC, out long dataFileSize)
{
byte[] binaryData = FileUtility.ReadAllBytes(filePath);
BufferReader buffer = new BufferReader(binaryData);
dataFileCRC = buffer.ReadUTF8();
dataFileCRC = buffer.ReadUInt32();
dataFileSize = buffer.ReadInt64();
}
#endregion

View File

@@ -7,10 +7,10 @@ namespace YooAsset
{
public string InfoFilePath { private set; get; }
public string DataFilePath { private set; get; }
public string DataFileCRC { private set; get; }
public uint DataFileCRC { private set; get; }
public long DataFileSize { private set; get; }
public RecordFileElement(string infoFilePath, string dataFilePath, string dataFileCRC, long dataFileSize)
public RecordFileElement(string infoFilePath, string dataFilePath, uint dataFileCRC, long dataFileSize)
{
InfoFilePath = infoFilePath;
DataFilePath = dataFilePath;

View File

@@ -4,7 +4,7 @@ namespace YooAsset
internal class TempFileElement
{
public string TempFilePath { private set; get; }
public string TempFileCRC { private set; get; }
public uint TempFileCRC { private set; get; }
public long TempFileSize { private set; get; }
/// <summary>
@@ -12,7 +12,7 @@ namespace YooAsset
/// </summary>
public volatile int Result = 0;
public TempFileElement(string filePath, string fileCRC, long fileSize)
public TempFileElement(string filePath, uint fileCRC, long fileSize)
{
TempFilePath = filePath;
TempFileCRC = fileCRC;

View File

@@ -10,7 +10,7 @@ namespace YooAsset
public string DataFilePath { private set; get; }
public string InfoFilePath { private set; get; }
public string DataFileCRC;
public uint DataFileCRC;
public long DataFileSize;
/// <summary>

View File

@@ -111,7 +111,7 @@ namespace YooAsset
if (_verifyCacheFilesOp.Status == EOperationStatus.Succeed)
{
_steps = ESteps.CreateDownloadCenter;
YooLogger.Log($"Package '{_fileSystem.PackageName}' cached files count : {_fileSystem.FileCount}");
YooLogger.Log($"Package '{_fileSystem.PackageName}' '{_fileSystem.GetType().Name}' cached files count : {_fileSystem.FileCount}");
}
else
{

View File

@@ -49,16 +49,25 @@ namespace YooAsset
}
else
{
_steps = ESteps.DownloadFile;
if (_fileSystem.DisableOnDemandDownload)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"The bundle not cached : {_bundle.BundleName}";
YooLogger.Warning(Error);
}
else
{
_steps = ESteps.DownloadFile;
}
}
}
if (_steps == ESteps.DownloadFile)
{
// 注意边玩边下下载器引用计数没有Release
if (_downloadFileOp == null)
{
DownloadFileOptions options = new DownloadFileOptions(int.MaxValue, 60);
DownloadFileOptions options = new DownloadFileOptions(int.MaxValue);
_downloadFileOp = _fileSystem.DownloadFileAsync(_bundle, options);
_downloadFileOp.StartOperation();
AddChildOperation(_downloadFileOp);
@@ -228,9 +237,6 @@ namespace YooAsset
{
if (ExecuteWhileDone())
{
if (_downloadFileOp != null && _downloadFileOp.Status == EOperationStatus.Failed)
YooLogger.Error($"Try load bundle {_bundle.BundleName} from remote !");
_steps = ESteps.Done;
break;
}
@@ -306,10 +312,9 @@ namespace YooAsset
if (_steps == ESteps.DownloadFile)
{
// 注意边玩边下下载器引用计数没有Release
if (_downloadFileOp == null)
{
DownloadFileOptions options = new DownloadFileOptions(int.MaxValue, 60);
DownloadFileOptions options = new DownloadFileOptions(int.MaxValue);
_downloadFileOp = _fileSystem.DownloadFileAsync(_bundle, options);
_downloadFileOp.StartOperation();
AddChildOperation(_downloadFileOp);
@@ -360,10 +365,6 @@ namespace YooAsset
{
if (ExecuteWhileDone())
{
//TODO 拷贝本地文件失败也会触发该错误!
if (_downloadFileOp != null && _downloadFileOp.Status == EOperationStatus.Failed)
YooLogger.Error($"Try load bundle {_bundle.BundleName} from remote !");
_steps = ESteps.Done;
break;
}

View File

@@ -6,8 +6,8 @@ namespace YooAsset
internal class DownloadCenterOperation : AsyncOperationBase
{
private readonly DefaultCacheFileSystem _fileSystem;
protected readonly Dictionary<string, DefaultDownloadFileOperation> _downloaders = new Dictionary<string, DefaultDownloadFileOperation>(1000);
protected readonly List<string> _removeDownloadList = new List<string>(1000);
protected readonly Dictionary<string, UnityDownloadFileOperation> _downloaders = new Dictionary<string, UnityDownloadFileOperation>(1000);
protected readonly List<string> _removeList = new List<string>(1000);
public DownloadCenterOperation(DefaultCacheFileSystem fileSystem)
{
@@ -19,31 +19,34 @@ namespace YooAsset
internal override void InternalUpdate()
{
// 获取可移除的下载器集合
_removeDownloadList.Clear();
_removeList.Clear();
foreach (var valuePair in _downloaders)
{
var downloader = valuePair.Value;
downloader.UpdateOperation();
if (downloader.IsDone)
{
_removeList.Add(valuePair.Key);
continue;
}
// 注意:主动终止引用计数为零的下载任务
if (downloader.RefCount <= 0)
{
_removeDownloadList.Add(valuePair.Key);
_removeList.Add(valuePair.Key);
downloader.AbortOperation();
continue;
}
if (downloader.IsDone)
{
_removeDownloadList.Add(valuePair.Key);
continue;
}
}
// 移除下载器
foreach (var key in _removeDownloadList)
foreach (var key in _removeList)
{
_downloaders.Remove(key);
if (_downloaders.TryGetValue(key, out var downloader))
{
Childs.Remove(downloader);
_downloaders.Remove(key);
}
}
// 最大并发数检测
@@ -74,41 +77,41 @@ namespace YooAsset
/// <summary>
/// 创建下载任务
/// </summary>
public FSDownloadFileOperation DownloadFileAsync(PackageBundle bundle, DownloadFileOptions options)
public UnityDownloadFileOperation DownloadFileAsync(PackageBundle bundle, string url)
{
// 查询旧的下载器
if (_downloaders.TryGetValue(bundle.BundleGUID, out var oldDownloader))
{
oldDownloader.Reference();
return oldDownloader;
}
// 设置请求URL
if (string.IsNullOrEmpty(options.ImportFilePath))
// 创建新的下载器
UnityDownloadFileOperation newDownloader;
bool isRequestLocalFile = DownloadSystemHelper.IsRequestLocalFile(url);
if (isRequestLocalFile)
{
options.MainURL = _fileSystem.RemoteServices.GetRemoteMainURL(bundle.FileName);
options.FallbackURL = _fileSystem.RemoteServices.GetRemoteFallbackURL(bundle.FileName);
newDownloader = new UnityDownloadLocalFileOperation(_fileSystem, bundle, url);
AddChildOperation(newDownloader);
_downloaders.Add(bundle.BundleGUID, newDownloader);
}
else
{
// 注意:把本地文件路径指定为远端下载地址
options.MainURL = DownloadSystemHelper.ConvertToWWWPath(options.ImportFilePath);
options.FallbackURL = options.MainURL;
if (bundle.FileSize >= _fileSystem.ResumeDownloadMinimumSize)
{
newDownloader = new UnityDownloadResumeFileOperation(_fileSystem, bundle, url);
AddChildOperation(newDownloader);
_downloaders.Add(bundle.BundleGUID, newDownloader);
}
else
{
newDownloader = new UnityDownloadNormalFileOperation(_fileSystem, bundle, url);
AddChildOperation(newDownloader);
_downloaders.Add(bundle.BundleGUID, newDownloader);
}
}
// 创建新的下载器
DefaultDownloadFileOperation newDownloader;
if (bundle.FileSize >= _fileSystem.ResumeDownloadMinimumSize)
{
newDownloader = new DownloadResumeFileOperation(_fileSystem, bundle, options);
AddChildOperation(newDownloader);
_downloaders.Add(bundle.BundleGUID, newDownloader);
}
else
{
newDownloader = new DownloadNormalFileOperation(_fileSystem, bundle, options);
AddChildOperation(newDownloader);
_downloaders.Add(bundle.BundleGUID, newDownloader);
}
newDownloader.Reference();
return newDownloader;
}

View File

@@ -1,87 +0,0 @@
using System;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
namespace YooAsset
{
/// <summary>
/// 支持Unity2018版本的断点续传下载器
/// </summary>
internal class DownloadHandlerFileRange : DownloadHandlerScript
{
private string _fileSavePath;
private long _fileTotalSize;
private UnityWebRequest _webRequest;
private FileStream _fileStream;
private long _localFileSize = 0;
private long _curFileSize = 0;
public DownloadHandlerFileRange(string fileSavePath, long fileTotalSize, UnityWebRequest webRequest) : base(new byte[1024 * 1024])
{
_fileSavePath = fileSavePath;
_fileTotalSize = fileTotalSize;
_webRequest = webRequest;
if (File.Exists(fileSavePath))
{
FileInfo fileInfo = new FileInfo(fileSavePath);
_localFileSize = fileInfo.Length;
}
_fileStream = new FileStream(_fileSavePath, FileMode.Append, FileAccess.Write);
_curFileSize = _localFileSize;
}
protected override bool ReceiveData(byte[] data, int dataLength)
{
if (data == null || dataLength == 0 || _webRequest.responseCode >= 400)
return false;
if (_fileStream == null)
return false;
_fileStream.Write(data, 0, dataLength);
_curFileSize += dataLength;
return true;
}
/// <summary>
/// UnityWebRequest.downloadHandler.data
/// </summary>
protected override byte[] GetData()
{
return null;
}
/// <summary>
/// UnityWebRequest.downloadHandler.text
/// </summary>
protected override string GetText()
{
return null;
}
/// <summary>
/// UnityWebRequest.downloadProgress
/// </summary>
protected override float GetProgress()
{
return _fileTotalSize == 0 ? 0 : ((float)_curFileSize) / _fileTotalSize;
}
/// <summary>
/// 释放下载句柄
/// </summary>
public void Cleanup()
{
if (_fileStream != null)
{
_fileStream.Flush();
_fileStream.Dispose();
_fileStream = null;
}
}
}
}

View File

@@ -1,208 +0,0 @@
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
namespace YooAsset
{
internal sealed class DownloadNormalFileOperation : DefaultDownloadFileOperation
{
private readonly DefaultCacheFileSystem _fileSystem;
private VerifyTempFileOperation _verifyOperation;
private bool _isReuqestLocalFile;
private string _tempFilePath;
private ESteps _steps = ESteps.None;
internal DownloadNormalFileOperation(DefaultCacheFileSystem fileSystem, PackageBundle bundle, DownloadFileOptions options) : base(bundle, options)
{
_fileSystem = fileSystem;
}
internal override void InternalStart()
{
_isReuqestLocalFile = DownloadSystemHelper.IsRequestLocalFile(Options.MainURL);
_tempFilePath = _fileSystem.GetTempFilePath(Bundle);
_steps = ESteps.CheckExists;
}
internal override void InternalUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
// 检测文件是否存在
if (_steps == ESteps.CheckExists)
{
if (_fileSystem.Exists(Bundle))
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
else
{
_steps = ESteps.CreateRequest;
}
}
// 创建下载器
if (_steps == ESteps.CreateRequest)
{
FileUtility.CreateFileDirectory(_tempFilePath);
// 删除临时文件
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
// 获取请求地址
_requestURL = GetRequestURL();
// 重置请求
ResetRequestFiled();
// 创建下载器
CreateWebRequest();
_steps = ESteps.CheckRequest;
}
// 检测下载结果
if (_steps == ESteps.CheckRequest)
{
DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = (long)_webRequest.downloadedBytes;
Progress = DownloadProgress;
if (_webRequest.isDone == false)
{
CheckRequestTimeout();
return;
}
// 检查网络错误
if (CheckRequestResult())
_steps = ESteps.VerifyTempFile;
else
_steps = ESteps.TryAgain;
// 注意:最终释放请求器
DisposeWebRequest();
}
// 验证下载文件
if (_steps == ESteps.VerifyTempFile)
{
var element = new TempFileElement(_tempFilePath, Bundle.FileCRC, Bundle.FileSize);
_verifyOperation = new VerifyTempFileOperation(element);
_verifyOperation.StartOperation();
AddChildOperation(_verifyOperation);
_steps = ESteps.CheckVerifyTempFile;
}
// 等待验证完成
if (_steps == ESteps.CheckVerifyTempFile)
{
if (IsWaitForAsyncComplete)
_verifyOperation.WaitForAsyncComplete();
_verifyOperation.UpdateOperation();
if (_verifyOperation.IsDone == false)
return;
if (_verifyOperation.Status == EOperationStatus.Succeed)
{
if (_fileSystem.WriteCacheBundleFile(Bundle, _tempFilePath))
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"{_fileSystem.GetType().FullName} failed to write file !";
YooLogger.Error(Error);
}
}
else
{
_steps = ESteps.TryAgain;
Error = _verifyOperation.Error;
}
// 注意:验证完成后直接删除文件
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
}
// 重新尝试下载
if (_steps == ESteps.TryAgain)
{
//TODO 拷贝本地文件失败后不再尝试!
if (_isReuqestLocalFile)
{
Status = EOperationStatus.Failed;
_steps = ESteps.Done;
YooLogger.Error(Error);
return;
}
if (FailedTryAgain <= 0)
{
Status = EOperationStatus.Failed;
_steps = ESteps.Done;
YooLogger.Error(Error);
return;
}
_tryAgainTimer += Time.unscaledDeltaTime;
if (_tryAgainTimer > 1f)
{
FailedTryAgain--;
_steps = ESteps.CreateRequest;
YooLogger.Warning(Error);
}
}
}
internal override void InternalAbort()
{
_steps = ESteps.Done;
DisposeWebRequest();
}
internal override void InternalWaitForAsyncComplete()
{
while (true)
{
//TODO 如果是导入或解压本地文件,执行等待完毕
if (_isReuqestLocalFile)
{
InternalUpdate();
if (IsDone)
break;
}
else
{
if (ExecuteWhileDone())
{
_steps = ESteps.Done;
break;
}
}
}
}
private void CreateWebRequest()
{
_webRequest = DownloadSystemHelper.NewUnityWebRequestGet(_requestURL);
DownloadHandlerFile handler = new DownloadHandlerFile(_tempFilePath);
handler.removeFileOnAbort = true;
_webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true;
_webRequest.SendWebRequest();
}
private void DisposeWebRequest()
{
if (_webRequest != null)
{
//注意引擎底层会自动调用Abort方法
_webRequest.Dispose();
_webRequest = null;
}
}
}
}

View File

@@ -0,0 +1,164 @@
using UnityEngine;
namespace YooAsset
{
internal class DownloadPackageBundleOperation : FSDownloadFileOperation
{
protected enum ESteps
{
None,
CheckExists,
CreateRequest,
CheckRequest,
TryAgain,
Done,
}
// 下载参数
protected readonly DefaultCacheFileSystem _fileSystem;
protected readonly DownloadFileOptions _options;
private UnityDownloadFileOperation _unityDownloadFileOp;
protected int _requestCount = 0;
protected float _tryAgainTimer;
protected int _failedTryAgain;
private ESteps _steps = ESteps.None;
internal DownloadPackageBundleOperation(DefaultCacheFileSystem fileSystem, PackageBundle bundle, DownloadFileOptions options) : base(bundle)
{
_fileSystem = fileSystem;
_options = options;
_failedTryAgain = options.FailedTryAgain;
}
internal override void InternalStart()
{
_steps = ESteps.CheckExists;
}
internal override void InternalUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
// 检测文件是否存在
if (_steps == ESteps.CheckExists)
{
if (_fileSystem.Exists(Bundle))
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
else
{
_steps = ESteps.CreateRequest;
}
}
// 创建下载器
if (_steps == ESteps.CreateRequest)
{
if (_options.IsValid() == false)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = "Download file options is invalid !";
Debug.Log(Error);
return;
}
string url = GetRequestURL();
_unityDownloadFileOp = _fileSystem.DownloadCenter.DownloadFileAsync(Bundle, url);
_steps = ESteps.CheckRequest;
}
// 检测下载结果
if (_steps == ESteps.CheckRequest)
{
if (IsWaitForAsyncComplete)
_unityDownloadFileOp.WaitForAsyncComplete();
// 因为并发数量限制,下载器可能被挂起!
if (_unityDownloadFileOp.Status == EOperationStatus.None)
return;
_unityDownloadFileOp.UpdateOperation();
Progress = _unityDownloadFileOp.Progress;
DownloadedBytes = _unityDownloadFileOp.DownloadedBytes;
DownloadProgress = _unityDownloadFileOp.DownloadProgress;
if (_unityDownloadFileOp.IsDone == false)
return;
if (_unityDownloadFileOp.Status == EOperationStatus.Succeed)
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
else
{
if (IsWaitForAsyncComplete == false && _failedTryAgain > 0)
{
_steps = ESteps.TryAgain;
YooLogger.Warning($"Failed download : {_unityDownloadFileOp.URL} Try again !");
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _unityDownloadFileOp.Error;
YooLogger.Error(Error);
}
}
}
// 重新尝试下载
if (_steps == ESteps.TryAgain)
{
_tryAgainTimer += Time.unscaledDeltaTime;
if (_tryAgainTimer > 1f)
{
_tryAgainTimer = 0f;
_failedTryAgain--;
Progress = 0f;
DownloadProgress = 0f;
DownloadedBytes = 0;
_steps = ESteps.CreateRequest;
}
}
}
internal override void InternalWaitForAsyncComplete()
{
while (true)
{
if (ExecuteWhileDone())
{
_steps = ESteps.Done;
break;
}
}
}
internal override void InternalAbort()
{
// 注意:取消下载任务的时候引用计数减一
if (_steps != ESteps.Done)
{
if (_unityDownloadFileOp != null)
{
_unityDownloadFileOp.Release();
}
}
}
/// <summary>
/// 获取网络请求地址
/// </summary>
protected string GetRequestURL()
{
// 轮流返回请求地址
_requestCount++;
if (_requestCount % 2 == 0)
return _options.FallbackURL;
else
return _options.MainURL;
}
}
}

View File

@@ -1,252 +0,0 @@
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
namespace YooAsset
{
internal sealed class DownloadResumeFileOperation : DefaultDownloadFileOperation
{
private readonly DefaultCacheFileSystem _fileSystem;
private DownloadHandlerFileRange _downloadHandle;
private VerifyTempFileOperation _verifyOperation;
private bool _isReuqestLocalFile;
private long _fileOriginLength = 0;
private string _tempFilePath;
private ESteps _steps = ESteps.None;
internal DownloadResumeFileOperation(DefaultCacheFileSystem fileSystem, PackageBundle bundle, DownloadFileOptions options) : base(bundle, options)
{
_fileSystem = fileSystem;
}
internal override void InternalStart()
{
_isReuqestLocalFile = DownloadSystemHelper.IsRequestLocalFile(Options.MainURL);
_tempFilePath = _fileSystem.GetTempFilePath(Bundle);
_steps = ESteps.CheckExists;
}
internal override void InternalUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
// 检测文件是否存在
if (_steps == ESteps.CheckExists)
{
if (_fileSystem.Exists(Bundle))
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
else
{
_steps = ESteps.CreateRequest;
}
}
// 创建下载器
if (_steps == ESteps.CreateRequest)
{
FileUtility.CreateFileDirectory(_tempFilePath);
// 获取请求地址
_requestURL = GetRequestURL();
// 重置变量
ResetRequestFiled();
// 获取下载起始位置
_fileOriginLength = 0;
long fileBeginLength = -1;
if (File.Exists(_tempFilePath))
{
FileInfo fileInfo = new FileInfo(_tempFilePath);
if (fileInfo.Length >= Bundle.FileSize)
{
// 删除临时文件
File.Delete(_tempFilePath);
}
else
{
fileBeginLength = fileInfo.Length;
_fileOriginLength = fileBeginLength;
DownloadedBytes = _fileOriginLength;
}
}
// 创建下载器
CreateWebRequest(fileBeginLength);
_steps = ESteps.CheckRequest;
}
// 检测下载结果
if (_steps == ESteps.CheckRequest)
{
DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = _fileOriginLength + (long)_webRequest.downloadedBytes;
if (_webRequest.isDone == false)
{
CheckRequestTimeout();
return;
}
// 检查网络错误
if (CheckRequestResult())
_steps = ESteps.VerifyTempFile;
else
_steps = ESteps.TryAgain;
// 在遇到特殊错误的时候删除文件
ClearTempFileWhenError();
// 注意:最终释放请求器
DisposeWebRequest();
}
// 验证下载文件
if (_steps == ESteps.VerifyTempFile)
{
var element = new TempFileElement(_tempFilePath, Bundle.FileCRC, Bundle.FileSize);
_verifyOperation = new VerifyTempFileOperation(element);
_verifyOperation.StartOperation();
AddChildOperation(_verifyOperation);
_steps = ESteps.CheckVerifyTempFile;
}
// 等待验证完成
if (_steps == ESteps.CheckVerifyTempFile)
{
if (IsWaitForAsyncComplete)
_verifyOperation.WaitForAsyncComplete();
_verifyOperation.UpdateOperation();
if (_verifyOperation.IsDone == false)
return;
if (_verifyOperation.Status == EOperationStatus.Succeed)
{
if (_fileSystem.WriteCacheBundleFile(Bundle, _tempFilePath))
{
Status = EOperationStatus.Succeed;
_steps = ESteps.Done;
}
else
{
Error = $"{_fileSystem.GetType().FullName} failed to write file !";
Status = EOperationStatus.Failed;
_steps = ESteps.Done;
}
}
else
{
Error = _verifyOperation.Error;
_steps = ESteps.TryAgain;
}
// 注意:验证完成后直接删除文件
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
}
// 重新尝试下载
if (_steps == ESteps.TryAgain)
{
//TODO 拷贝本地文件失败后不再尝试!
if (_isReuqestLocalFile)
{
Status = EOperationStatus.Failed;
_steps = ESteps.Done;
YooLogger.Error(Error);
return;
}
if (FailedTryAgain <= 0)
{
Status = EOperationStatus.Failed;
_steps = ESteps.Done;
YooLogger.Error(Error);
return;
}
_tryAgainTimer += Time.unscaledDeltaTime;
if (_tryAgainTimer > 1f)
{
FailedTryAgain--;
_steps = ESteps.CreateRequest;
YooLogger.Warning(Error);
}
}
}
internal override void InternalAbort()
{
_steps = ESteps.Done;
DisposeWebRequest();
}
internal override void InternalWaitForAsyncComplete()
{
while (true)
{
//TODO 如果是导入或解压本地文件,执行等待完毕
if (_isReuqestLocalFile)
{
InternalUpdate();
if (IsDone)
break;
}
else
{
if (ExecuteWhileDone())
{
_steps = ESteps.Done;
break;
}
}
}
}
private void CreateWebRequest(long beginLength)
{
_webRequest = DownloadSystemHelper.NewUnityWebRequestGet(_requestURL);
#if UNITY_2019_4_OR_NEWER
var handler = new DownloadHandlerFile(_tempFilePath, true);
handler.removeFileOnAbort = false;
#else
var handler = new DownloadHandlerFileRange(FileSavePath, Bundle.FileSize, _webRequest);
_downloadHandle = handler;
#endif
_webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true;
if (beginLength > 0)
_webRequest.SetRequestHeader("Range", $"bytes={beginLength}-");
_webRequest.SendWebRequest();
}
private void DisposeWebRequest()
{
if (_downloadHandle != null)
{
_downloadHandle.Cleanup();
_downloadHandle = null;
}
if (_webRequest != null)
{
//注意引擎底层会自动调用Abort方法
_webRequest.Dispose();
_webRequest = null;
}
}
private void ClearTempFileWhenError()
{
if (_fileSystem.ResumeDownloadResponseCodes == null)
return;
//说明:如果遇到以下错误返回码,验证失败直接删除文件
if (_fileSystem.ResumeDownloadResponseCodes.Contains(HttpCode))
{
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
}
}
}
}

View File

@@ -75,7 +75,7 @@ namespace YooAsset
{
if (_deserializer == null)
{
_deserializer = new DeserializeManifestOperation(_fileData);
_deserializer = new DeserializeManifestOperation(_fileSystem.ManifestServices, _fileData);
_deserializer.StartOperation();
AddChildOperation(_deserializer);
}

View File

@@ -0,0 +1,98 @@

namespace YooAsset
{
internal abstract class UnityDownloadFileOperation : UnityWebRequestOperation
{
protected enum ESteps
{
None,
CreateRequest,
Download,
CopyLocalFile,
VerifyFile,
Done,
}
protected readonly DefaultCacheFileSystem _fileSystem;
protected readonly PackageBundle _bundle;
protected readonly string _tempFilePath;
private bool _watchDogInit = false;
private bool _watchDogAborted = false;
private ulong _lastDownloadBytes;
private double _lastGetDataTime;
/// <summary>
/// 引用计数
/// </summary>
public int RefCount { private set; get; }
internal UnityDownloadFileOperation(DefaultCacheFileSystem fileSystem, PackageBundle bundle, string url) : base(url)
{
_fileSystem = fileSystem;
_bundle = bundle;
_tempFilePath = _fileSystem.GetTempFilePath(bundle);
}
internal override string InternalGetDesc()
{
return $"RefCount : {RefCount}";
}
/// <summary>
/// 更新看门狗监测
/// 说明:监控时间范围内,如果没有接收到任何下载数据,那么直接终止任务!
/// </summary>
protected void UpdateWatchDog()
{
if (_fileSystem.DownloadWatchDogTime == int.MaxValue)
return;
if (_watchDogAborted)
return;
#if UNITY_2020_3_OR_NEWER
double realtimeSinceStartup = UnityEngine.Time.realtimeSinceStartupAsDouble;
#else
double realtimeSinceStartup = UnityEngine.Time.realtimeSinceStartup;
#endif
if (_watchDogInit == false)
{
_watchDogInit = true;
_lastDownloadBytes = 0;
_lastGetDataTime = realtimeSinceStartup;
}
if (_webRequest.downloadedBytes != _lastDownloadBytes)
{
_lastDownloadBytes = _webRequest.downloadedBytes;
_lastGetDataTime = realtimeSinceStartup;
}
else
{
double deltaTime = realtimeSinceStartup - _lastGetDataTime;
if (deltaTime > _fileSystem.DownloadWatchDogTime)
{
_watchDogAborted = true;
InternalAbort(); //终止网络请求
}
}
}
/// <summary>
/// 减少引用计数
/// </summary>
public void Release()
{
RefCount--;
}
/// <summary>
/// 增加引用计数
/// </summary>
public void Reference()
{
RefCount++;
}
}
}

View File

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

View File

@@ -0,0 +1,170 @@
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
namespace YooAsset
{
internal sealed class UnityDownloadLocalFileOperation : UnityDownloadFileOperation
{
private VerifyTempFileOperation _verifyOperation;
private ESteps _steps = ESteps.None;
internal UnityDownloadLocalFileOperation(DefaultCacheFileSystem fileSystem, PackageBundle bundle, string url)
: base(fileSystem, bundle, url)
{
}
internal override void InternalStart()
{
if (_fileSystem.CopyLocalFileServices != null)
_steps = ESteps.CopyLocalFile;
else
_steps = ESteps.CreateRequest;
}
internal override void InternalUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
// 创建下载器
if (_steps == ESteps.CreateRequest)
{
FileUtility.CreateFileDirectory(_tempFilePath);
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
CreateWebRequest();
_steps = ESteps.Download;
}
// 检测下载结果
if (_steps == ESteps.Download)
{
DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = (long)_webRequest.downloadedBytes;
Progress = DownloadProgress;
UpdateWatchDog();
if (_webRequest.isDone == false)
return;
// 检查网络错误
if (CheckRequestResult())
{
_steps = ESteps.VerifyFile;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
}
// 注意:最终释放请求器
DisposeRequest();
}
// 拷贝内置文件
if (_steps == ESteps.CopyLocalFile)
{
FileUtility.CreateFileDirectory(_tempFilePath);
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
try
{
//TODO 团结引擎,在某些机型(红米),拷贝包内文件会小概率失败!需要借助其它方式来拷贝包内文件。
var localFileInfo = new LocalFileInfo();
localFileInfo.PackageName = _fileSystem.PackageName;
localFileInfo.BundleName = _bundle.BundleName;
localFileInfo.SourceFileURL = _requestURL;
_fileSystem.CopyLocalFileServices.CopyFile(localFileInfo, _tempFilePath);
if (File.Exists(_tempFilePath))
{
DownloadProgress = 1f;
DownloadedBytes = _bundle.FileSize;
Progress = DownloadProgress;
_steps = ESteps.VerifyFile;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Failed copy local file : {_requestURL}";
}
}
catch (System.Exception ex)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Failed copy local file : {ex.Message}";
}
}
// 验证下载文件
if (_steps == ESteps.VerifyFile)
{
if (_verifyOperation == null)
{
var element = new TempFileElement(_tempFilePath, _bundle.FileCRC, _bundle.FileSize);
_verifyOperation = new VerifyTempFileOperation(element);
_verifyOperation.StartOperation();
AddChildOperation(_verifyOperation);
}
if (IsWaitForAsyncComplete)
_verifyOperation.WaitForAsyncComplete();
_verifyOperation.UpdateOperation();
if (_verifyOperation.IsDone == false)
return;
if (_verifyOperation.Status == EOperationStatus.Succeed)
{
if (_fileSystem.WriteCacheBundleFile(_bundle, _tempFilePath))
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"{_fileSystem.GetType().FullName} failed to write file !";
}
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _verifyOperation.Error;
}
// 注意:验证完成后直接删除文件
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
}
}
internal override void InternalWaitForAsyncComplete()
{
while (true)
{
//TODO 等待导入或解压本地文件完毕,该操作会挂起主线程!
InternalUpdate();
if (IsDone)
break;
// 短暂休眠避免完全卡死
System.Threading.Thread.Sleep(1);
}
}
private void CreateWebRequest()
{
DownloadHandlerFile handler = new DownloadHandlerFile(_tempFilePath);
handler.removeFileOnAbort = true;
_webRequest = DownloadSystemHelper.NewUnityWebRequestGet(_requestURL);
_webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true;
_webRequest.SendWebRequest();
}
}
}

View File

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

View File

@@ -0,0 +1,124 @@
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
namespace YooAsset
{
internal sealed class UnityDownloadNormalFileOperation : UnityDownloadFileOperation
{
private VerifyTempFileOperation _verifyOperation;
private ESteps _steps = ESteps.None;
internal UnityDownloadNormalFileOperation(DefaultCacheFileSystem fileSystem, PackageBundle bundle, string url)
: base(fileSystem, bundle, url)
{
}
internal override void InternalStart()
{
_steps = ESteps.CreateRequest;
}
internal override void InternalUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
// 创建下载器
if (_steps == ESteps.CreateRequest)
{
FileUtility.CreateFileDirectory(_tempFilePath);
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
CreateWebRequest();
_steps = ESteps.Download;
}
// 检测下载结果
if (_steps == ESteps.Download)
{
DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = (long)_webRequest.downloadedBytes;
Progress = DownloadProgress;
UpdateWatchDog();
if (_webRequest.isDone == false)
return;
// 检查网络错误
if (CheckRequestResult())
{
_steps = ESteps.VerifyFile;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
}
// 注意:最终释放请求器
DisposeRequest();
}
// 验证下载文件
if (_steps == ESteps.VerifyFile)
{
if (_verifyOperation == null)
{
var element = new TempFileElement(_tempFilePath, _bundle.FileCRC, _bundle.FileSize);
_verifyOperation = new VerifyTempFileOperation(element);
_verifyOperation.StartOperation();
AddChildOperation(_verifyOperation);
}
if (IsWaitForAsyncComplete)
_verifyOperation.WaitForAsyncComplete();
_verifyOperation.UpdateOperation();
if (_verifyOperation.IsDone == false)
return;
if (_verifyOperation.Status == EOperationStatus.Succeed)
{
if (_fileSystem.WriteCacheBundleFile(_bundle, _tempFilePath))
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"{_fileSystem.GetType().FullName} failed to write file ! {_tempFilePath}";
}
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _verifyOperation.Error;
}
// 注意:验证完成后直接删除文件
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
}
}
internal override void InternalWaitForAsyncComplete()
{
if (_steps != ESteps.Done)
{
YooLogger.Error($"Try load bundle {_bundle.BundleName} from remote : {_requestURL} !");
}
}
private void CreateWebRequest()
{
DownloadHandlerFile handler = new DownloadHandlerFile(_tempFilePath);
handler.removeFileOnAbort = true;
_webRequest = DownloadSystemHelper.NewUnityWebRequestGet(_requestURL);
_webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true;
_webRequest.SendWebRequest();
}
}
}

View File

@@ -0,0 +1,158 @@
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
namespace YooAsset
{
internal sealed class UnityDownloadResumeFileOperation : UnityDownloadFileOperation
{
private VerifyTempFileOperation _verifyOperation;
private long _fileOriginLength = 0;
private ESteps _steps = ESteps.None;
internal UnityDownloadResumeFileOperation(DefaultCacheFileSystem fileSystem, PackageBundle bundle, string url)
: base(fileSystem, bundle, url)
{
}
internal override void InternalStart()
{
_steps = ESteps.CreateRequest;
}
internal override void InternalUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
// 创建下载器
if (_steps == ESteps.CreateRequest)
{
FileUtility.CreateFileDirectory(_tempFilePath);
// 获取下载起始位置
_fileOriginLength = 0;
long fileBeginLength = -1;
if (File.Exists(_tempFilePath))
{
FileInfo fileInfo = new FileInfo(_tempFilePath);
if (fileInfo.Length >= _bundle.FileSize)
{
File.Delete(_tempFilePath);
}
else
{
fileBeginLength = fileInfo.Length;
_fileOriginLength = fileBeginLength;
DownloadedBytes = _fileOriginLength;
}
}
CreateWebRequest(fileBeginLength);
_steps = ESteps.Download;
}
// 检测下载结果
if (_steps == ESteps.Download)
{
DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = _fileOriginLength + (long)_webRequest.downloadedBytes;
Progress = DownloadProgress;
UpdateWatchDog();
if (_webRequest.isDone == false)
return;
// 检查网络错误
if (CheckRequestResult())
{
_steps = ESteps.VerifyFile;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
}
// 在遇到特殊错误的时候删除文件
ClearTempFileWhenError();
// 注意:最终释放请求器
DisposeRequest();
}
// 验证下载文件
if (_steps == ESteps.VerifyFile)
{
if (_verifyOperation == null)
{
var element = new TempFileElement(_tempFilePath, _bundle.FileCRC, _bundle.FileSize);
_verifyOperation = new VerifyTempFileOperation(element);
_verifyOperation.StartOperation();
AddChildOperation(_verifyOperation);
}
if (IsWaitForAsyncComplete)
_verifyOperation.WaitForAsyncComplete();
_verifyOperation.UpdateOperation();
if (_verifyOperation.IsDone == false)
return;
if (_verifyOperation.Status == EOperationStatus.Succeed)
{
if (_fileSystem.WriteCacheBundleFile(_bundle, _tempFilePath))
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"{_fileSystem.GetType().FullName} failed to write file !";
}
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _verifyOperation.Error;
}
// 注意:验证完成后直接删除文件
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
}
}
internal override void InternalWaitForAsyncComplete()
{
if (_steps != ESteps.Done)
{
YooLogger.Error($"Try load bundle {_bundle.BundleName} from remote : {_requestURL} !");
}
}
private void ClearTempFileWhenError()
{
if (_fileSystem.ResumeDownloadResponseCodes == null)
return;
//说明:如果遇到以下错误返回码,验证失败直接删除文件
if (_fileSystem.ResumeDownloadResponseCodes.Contains(HttpCode))
{
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
}
}
private void CreateWebRequest(long fileBeginLength)
{
var handler = new DownloadHandlerFile(_tempFilePath, true);
handler.removeFileOnAbort = false;
_webRequest = DownloadSystemHelper.NewUnityWebRequestGet(_requestURL);
_webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true;
if (fileBeginLength > 0)
_webRequest.SetRequestHeader("Range", $"bytes={fileBeginLength}-");
_webRequest.SendWebRequest();
}
}
}

View File

@@ -54,11 +54,13 @@ namespace YooAsset
// 设置同时验证的最大数
ThreadPool.GetMaxThreads(out int workerThreads, out int ioThreads);
YooLogger.Log($"Work threads : {workerThreads}, IO threads : {ioThreads}");
_verifyMaxNum = Math.Min(workerThreads, ioThreads);
int threads = Math.Min(workerThreads, ioThreads);
_verifyMaxNum = Math.Min(threads, _fileSystem.FileVerifyMaxConcurrency);
_verifyTotalCount = fileCount;
if (_verifyMaxNum < 1)
_verifyMaxNum = 1;
YooLogger.Log($"Verify max concurrency : {_verifyMaxNum}");
_verifyingList = new List<VerifyFileElement>(_verifyMaxNum);
_steps = ESteps.UpdateVerify;
}

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