Compare commits

...

53 Commits

Author SHA1 Message Date
hevinci
9c05ac8cc2 Update CHANGELOG.md 2023-03-10 16:06:54 +08:00
hevinci
55d1eb145e Update package.json 2023-03-10 16:06:45 +08:00
hevinci
c8cdeb2ae1 update asset system 2023-03-10 15:53:28 +08:00
hevinci
9891ab23a2 update samples 2023-03-09 17:29:37 +08:00
hevinci
9739fe2b79 update samples 2023-03-09 17:28:40 +08:00
hevinci
c976221cbb update shader variant collector
修复了在unity2021下界面错乱的问题。
2023-03-09 15:33:48 +08:00
hevinci
8267904155 update editor code 2023-03-09 15:16:02 +08:00
hevinci
ef8a8ff497 update asset bundle builder 2023-03-09 10:29:14 +08:00
hevinci
2384921477 update asset bundle builder
修复了可编程构建管线,当项目里没有着色器,如果有引用内置着色器会导致打包失败的问题。
2023-03-08 19:39:20 +08:00
hevinci
985b05f29d update asset bundle builder
优化了打包逻辑,提高构建速度。
2023-03-08 19:27:09 +08:00
hevinci
5254fb65ef update asset bundle collector 2023-03-08 18:34:48 +08:00
hevinci
8ff666d5e2 update patch system 2023-03-08 12:48:57 +08:00
hevinci
ed77d6dc1f update decryption services 2023-03-08 12:22:09 +08:00
hevinci
7b41fd82a4 update asset system 2023-03-08 12:10:07 +08:00
hevinci
ac0112199d update asset bundle builder
修复了SBP打包,如果包含内置资源会打包失败的问题。
2023-03-06 20:18:41 +08:00
hevinci
ef5e1e65f9 fix #73
修复了同步加载原生文件,程序卡死的问题。
2023-03-06 20:05:34 +08:00
hevinci
b330d26b4f update asset bundle builder 2023-03-06 19:07:46 +08:00
hevinci
93d7c34454 update logger 2023-03-03 18:24:01 +08:00
hevinci
0bd5677e26 update runtime code 2023-03-03 18:21:56 +08:00
hevinci
22e2e978ef Merge branch 'main' of https://github.com/tuyoogame/YooAsset 2023-03-03 18:04:46 +08:00
hevinci
65c2651105 Update EditorHelper.cs 2023-03-03 18:04:44 +08:00
何冠峰
ef13e19c48 Merge pull request #72 from HXiaoMing/feat-custom-logger
feat(YooLogger):支持自定义日志处理,方便收集线上问题
2023-03-03 18:03:21 +08:00
hevinci
39ffad6da6 Update CHANGELOG.md 2023-03-03 17:28:51 +08:00
hevinci
13924fca13 Update package.json 2023-03-03 17:28:42 +08:00
hevinci
438f006d1d update samples 2023-03-03 17:28:24 +08:00
hevinci
6fb5626230 Update document 2023-03-03 17:28:03 +08:00
hevinci
ab29069af5 update download system
下载文件验证支持多线程。
2023-03-03 16:12:17 +08:00
hevinci
fc3ed28eda update samples 2023-03-03 11:53:22 +08:00
hevinci
46c9110b85 update asset bundle builder 2023-03-03 11:51:48 +08:00
hevinci
06b033ed36 update asset system
优化了资源加载器查询逻辑。
2023-03-03 11:23:15 +08:00
hevinci
ab96f3f28c update cache system
优化缓存系统的存储目录结构。
2023-03-01 20:35:01 +08:00
hevinci
295238cbb6 update asset system
优化资源对象加载耗时统计逻辑。
2023-03-01 18:23:47 +08:00
huanggongming
69125e967f feat(YooLogger):支持自定义日志处理,方便收集线上问题 2023-03-01 16:10:24 +08:00
hevinci
4f0f0e54ac update asset bundle collector
优化了资源收集界面,查看Collector主资源列表卡顿问题。
2023-03-01 11:03:52 +08:00
hevinci
a9a01b08dc update patch system 2023-03-01 10:50:38 +08:00
hevinci
c27a3e105c update asset bundle builder
修复SBP构建时,如果有原生文件导致报错的问题。
2023-02-28 19:21:13 +08:00
hevinci
3cfc084e62 update cache system 2023-02-28 19:17:05 +08:00
hevinci
7c1873e861 update asset bundle builder
修复在构建过程中发生异常后进度条未消失的问题。
2023-02-28 19:01:32 +08:00
hevinci
c57c313dbe update samples 2023-02-28 18:26:10 +08:00
hevinci
19cf9c0129 update download system
修复关闭编辑器时的报错。
2023-02-28 18:25:48 +08:00
hevinci
ebcb05cc55 update cache system
优化了缓存系统初始化逻辑,支持分帧获取所有缓存文件。
2023-02-28 18:25:27 +08:00
hevinci
7c4dbb1f38 update asset bundle builder 2023-02-27 19:10:56 +08:00
hevinci
091b46ccaf update samples 2023-02-27 19:02:24 +08:00
hevinci
4da2bf441f update shader variant collector
着色器变种收集界面增加单次照射数量的控制。
2023-02-27 19:02:16 +08:00
hevinci
365ed560f6 update asset bundle builder
优化资源包引用关系计算效率。
2023-02-27 18:11:51 +08:00
hevinci
bcf6372602 update download system 2023-02-24 19:45:05 +08:00
hevinci
a5e24be5d4 update asset bundle builder
修复资源包存在循环依赖的情况下打包卡死的问题。
2023-02-24 18:49:45 +08:00
hevinci
cdaf6f0dca update samples 2023-02-24 16:52:50 +08:00
何冠峰
e38d0bc6d0 Merge pull request #70 from HXiaoMing/feat-custom-download-request
feat(DownloadSystem):支持自定义下载请求
2023-02-24 15:58:44 +08:00
huanggongming
eb16ba8365 feat(DownloadSystem):支持自定义下载请求 2023-02-24 12:18:18 +08:00
hevinci
3beb4f53d6 Update document 2023-02-24 12:13:18 +08:00
hevinci
f8ba0c9753 update asset system
修复引用链无效的问题。
2023-02-24 12:12:44 +08:00
hevinci
0232e5adec Update document 2023-02-23 12:15:41 +08:00
130 changed files with 1785 additions and 804 deletions

View File

@@ -2,6 +2,66 @@
All notable changes to this package will be documented in this file. All notable changes to this package will be documented in this file.
## [1.4.8] - 2023-03-10
### Fixed
- 修复了同步加载原生文件,程序卡死的问题。
- 修复了可编程构建管线,当项目里没有着色器,如果有引用内置着色器会导致打包失败的问题。
- 修复了在Unity2021.3版本下着色器收集界面错乱的问题。
### Changed
- 优化了打包逻辑,提高构建速度。
- 支持自定义日志处理,方便收集线上问题。
```c#
public class YooAssets
{
/// <summary>
/// 初始化资源系统
/// </summary>
/// <param name="logger">自定义日志处理</param>
public static void Initialize(ILogger logger = null)
}
```
## [1.4.7] - 2023-03-03
### Fixed
- 修复了在运行时资源引用链无效的问题。
- 修复了在构建过程中发生异常后进度条未消失的问题。
- 修复了使用SBP构建管线如果有原生文件会导致打包失败的问题。
### Changed
- 支持自定义下载请求
```c#
/// <summary>
/// 设置下载系统参数,自定义下载请求
/// </summary>
public static void SetDownloadSystemUnityWebRequest(DownloadRequestDelegate requestDelegate)
```
- 优化了打包时资源包引用关系计算的逻辑。
- 优化了缓存系统初始化逻辑,支持分帧获取所有缓存文件。
- 优化了缓存系统的存储目录结构,提高了文件夹查询速度。
- 优化了在资源收集界面点击查看Collector主资源列表卡顿问题。
- 优化了资源对象加载耗时统计的逻辑,现在更加准确了。
- 优化了资源加载器查询逻辑。
- 优化了资源下载系统,下载文件的验证支持了多线程。
- 着色器变种收集界面增加单次照射数量的控制。
## [1.4.6-preview] - 2023-02-22 ## [1.4.6-preview] - 2023-02-22
### Changed ### Changed

View File

@@ -39,12 +39,6 @@ namespace YooAsset.Editor
var buildParametersContext = new BuildParametersContext(buildParameters); var buildParametersContext = new BuildParametersContext(buildParameters);
_buildContext.SetContextObject(buildParametersContext); _buildContext.SetContextObject(buildParametersContext);
// 是否显示LOG
if (buildParameters.BuildMode == EBuildMode.SimulateBuild)
BuildRunner.EnableLog = false;
else
BuildRunner.EnableLog = true;
// 创建构建节点 // 创建构建节点
List<IBuildTask> pipeline; List<IBuildTask> pipeline;
if (buildParameters.BuildPipeline == EBuildPipeline.BuiltinBuildPipeline) if (buildParameters.BuildPipeline == EBuildPipeline.BuiltinBuildPipeline)
@@ -57,7 +51,7 @@ namespace YooAsset.Editor
new TaskCopyRawFile(), //拷贝原生文件 new TaskCopyRawFile(), //拷贝原生文件
new TaskVerifyBuildResult(), //验证构建结果 new TaskVerifyBuildResult(), //验证构建结果
new TaskEncryption(), //加密资源文件 new TaskEncryption(), //加密资源文件
new TaskUpdateBuildInfo(), //更新构建信息 new TaskUpdatePatchInfo(), //更新补丁信息
new TaskCreatePatchManifest(), //创建清单文件 new TaskCreatePatchManifest(), //创建清单文件
new TaskCreateReport(), //创建报告文件 new TaskCreateReport(), //创建报告文件
new TaskCreatePatchPackage(), //制作补丁包 new TaskCreatePatchPackage(), //制作补丁包
@@ -74,7 +68,7 @@ namespace YooAsset.Editor
new TaskCopyRawFile(), //拷贝原生文件 new TaskCopyRawFile(), //拷贝原生文件
new TaskVerifyBuildResult_SBP(), //验证构建结果 new TaskVerifyBuildResult_SBP(), //验证构建结果
new TaskEncryption(), //加密资源文件 new TaskEncryption(), //加密资源文件
new TaskUpdateBuildInfo(), //更新构建信息 new TaskUpdatePatchInfo(), //更新补丁信息
new TaskCreatePatchManifest(), //创建清单文件 new TaskCreatePatchManifest(), //创建清单文件
new TaskCreateReport(), //创建报告文件 new TaskCreateReport(), //创建报告文件
new TaskCreatePatchPackage(), //制作补丁包 new TaskCreatePatchPackage(), //制作补丁包
@@ -86,19 +80,23 @@ namespace YooAsset.Editor
throw new NotImplementedException(); throw new NotImplementedException();
} }
// 初始化日志
BuildLogger.InitLogger(buildParameters.EnableLog);
// 执行构建流程 // 执行构建流程
var buildResult = BuildRunner.Run(pipeline, _buildContext); var buildResult = BuildRunner.Run(pipeline, _buildContext);
if (buildResult.Success) if (buildResult.Success)
{ {
buildResult.OutputPackageDirectory = buildParametersContext.GetPackageOutputDirectory(); buildResult.OutputPackageDirectory = buildParametersContext.GetPackageOutputDirectory();
Debug.Log($"{buildParameters.BuildMode} pipeline build succeed !"); BuildLogger.Log($"{buildParameters.BuildMode} pipeline build succeed !");
} }
else else
{ {
Debug.LogWarning($"{buildParameters.BuildMode} pipeline build failed !"); BuildLogger.Warning($"{buildParameters.BuildMode} pipeline build failed !");
Debug.LogError($"Build task failed : {buildResult.FailedTask}"); BuildLogger.Error($"Build task failed : {buildResult.FailedTask}");
Debug.LogError($"Build task error : {buildResult.FailedInfo}"); BuildLogger.Error($"Build task error : {buildResult.FailedInfo}");
} }
return buildResult; return buildResult;
} }
} }

View File

@@ -60,7 +60,7 @@ namespace YooAsset.Editor
// 加密服务类 // 加密服务类
_encryptionServicesClassTypes = GetEncryptionServicesClassTypes(); _encryptionServicesClassTypes = GetEncryptionServicesClassTypes();
_encryptionServicesClassNames = _encryptionServicesClassTypes.Select(t => t.FullName).ToList(); _encryptionServicesClassNames = _encryptionServicesClassTypes.Select(t => t.Name).ToList();
// 输出目录 // 输出目录
string defaultOutputRoot = AssetBundleBuilderHelper.GetDefaultOutputRoot(); string defaultOutputRoot = AssetBundleBuilderHelper.GetDefaultOutputRoot();

View File

@@ -18,6 +18,7 @@ namespace YooAsset.Editor
buildParameters.BuildMode = EBuildMode.SimulateBuild; buildParameters.BuildMode = EBuildMode.SimulateBuild;
buildParameters.PackageName = packageName; buildParameters.PackageName = packageName;
buildParameters.PackageVersion = "Simulate"; buildParameters.PackageVersion = "Simulate";
buildParameters.EnableLog = false;
AssetBundleBuilder builder = new AssetBundleBuilder(); AssetBundleBuilder builder = new AssetBundleBuilder();
var buildResult = builder.Run(buildParameters); var buildResult = builder.Run(buildParameters);

View File

@@ -8,6 +8,8 @@ namespace YooAsset.Editor
{ {
public class BuildMapContext : IContextObject public class BuildMapContext : IContextObject
{ {
private readonly Dictionary<string, BuildBundleInfo> _bundleInfoDic = new Dictionary<string, BuildBundleInfo>(10000);
/// <summary> /// <summary>
/// 参与构建的资源总数 /// 参与构建的资源总数
/// 说明:包括主动收集的资源以及其依赖的所有资源 /// 说明:包括主动收集的资源以及其依赖的所有资源
@@ -30,9 +32,15 @@ namespace YooAsset.Editor
public string ShadersBundleName; public string ShadersBundleName;
/// <summary> /// <summary>
/// 资源包列表 /// 资源包信息列表
/// </summary> /// </summary>
public readonly List<BuildBundleInfo> BundleInfos = new List<BuildBundleInfo>(1000); public Dictionary<string, BuildBundleInfo>.ValueCollection Collection
{
get
{
return _bundleInfoDic.Values;
}
}
/// <summary> /// <summary>
@@ -44,7 +52,7 @@ namespace YooAsset.Editor
if (string.IsNullOrEmpty(bundleName)) if (string.IsNullOrEmpty(bundleName))
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
if (TryGetBundleInfo(bundleName, out BuildBundleInfo bundleInfo)) if (_bundleInfoDic.TryGetValue(bundleName, out BuildBundleInfo bundleInfo))
{ {
bundleInfo.PackAsset(assetInfo); bundleInfo.PackAsset(assetInfo);
} }
@@ -52,33 +60,28 @@ namespace YooAsset.Editor
{ {
BuildBundleInfo newBundleInfo = new BuildBundleInfo(bundleName); BuildBundleInfo newBundleInfo = new BuildBundleInfo(bundleName);
newBundleInfo.PackAsset(assetInfo); newBundleInfo.PackAsset(assetInfo);
BundleInfos.Add(newBundleInfo); _bundleInfoDic.Add(bundleName, newBundleInfo);
} }
} }
/// <summary> /// <summary>
/// 获取所有的打包资源 /// 是否包含资源
/// </summary> /// </summary>
public List<BuildAssetInfo> GetAllAssets() public bool IsContainsBundle(string bundleName)
{ {
List<BuildAssetInfo> result = new List<BuildAssetInfo>(BundleInfos.Count); return _bundleInfoDic.ContainsKey(bundleName);
foreach (var bundleInfo in BundleInfos)
{
result.AddRange(bundleInfo.BuildinAssets);
}
return result;
} }
/// <summary> /// <summary>
/// 获取AssetBundle内构建的资源路径列表 /// 获取资源包信息如果没找到返回NULL
/// </summary> /// </summary>
public string[] GetBuildinAssetPaths(string bundleName) public BuildBundleInfo GetBundleInfo(string bundleName)
{ {
if (TryGetBundleInfo(bundleName, out BuildBundleInfo bundleInfo)) if (_bundleInfoDic.TryGetValue(bundleName, out BuildBundleInfo result))
{ {
return bundleInfo.GetBuildinAssetPaths(); return result;
} }
throw new Exception($"Not found {nameof(BuildBundleInfo)} : {bundleName}"); throw new Exception($"Not found bundle : {bundleName}");
} }
/// <summary> /// <summary>
@@ -86,8 +89,8 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public UnityEditor.AssetBundleBuild[] GetPipelineBuilds() public UnityEditor.AssetBundleBuild[] GetPipelineBuilds()
{ {
List<UnityEditor.AssetBundleBuild> builds = new List<UnityEditor.AssetBundleBuild>(BundleInfos.Count); List<UnityEditor.AssetBundleBuild> builds = new List<UnityEditor.AssetBundleBuild>(_bundleInfoDic.Count);
foreach (var bundleInfo in BundleInfos) foreach (var bundleInfo in _bundleInfoDic.Values)
{ {
if (bundleInfo.IsRawFile == false) if (bundleInfo.IsRawFile == false)
builds.Add(bundleInfo.CreatePipelineBuild()); builds.Add(bundleInfo.CreatePipelineBuild());
@@ -96,25 +99,15 @@ namespace YooAsset.Editor
} }
/// <summary> /// <summary>
/// 是否包含资源包 /// 创建着色器信息类
/// </summary> /// </summary>
public bool IsContainsBundle(string bundleName) public void CreateShadersBundleInfo(string shadersBundleName)
{ {
return TryGetBundleInfo(bundleName, out BuildBundleInfo bundleInfo); if (IsContainsBundle(shadersBundleName) == false)
}
public bool TryGetBundleInfo(string bundleName, out BuildBundleInfo result)
{
foreach (var bundleInfo in BundleInfos)
{ {
if (bundleInfo.BundleName == bundleName) var shaderBundleInfo = new BuildBundleInfo(shadersBundleName);
{ _bundleInfoDic.Add(shadersBundleName, shaderBundleInfo);
result = bundleInfo;
return true;
}
} }
result = null;
return false;
} }
} }
} }

View File

@@ -1,145 +0,0 @@
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset.Editor
{
public static class BuildMapCreater
{
/// <summary>
/// 执行资源构建上下文
/// </summary>
public static BuildMapContext CreateBuildMap(EBuildMode buildMode, string packageName)
{
Dictionary<string, BuildAssetInfo> buildAssetDic = new Dictionary<string, BuildAssetInfo>(1000);
// 1. 检测配置合法性
AssetBundleCollectorSettingData.Setting.CheckConfigError();
// 2. 获取所有收集器收集的资源
var buildResult = AssetBundleCollectorSettingData.Setting.GetPackageAssets(buildMode, packageName);
List<CollectAssetInfo> allCollectAssets = buildResult.CollectAssets;
// 3. 剔除未被引用的依赖项资源
List<CollectAssetInfo> removeDependList = new List<CollectAssetInfo>();
foreach (var collectAssetInfo in allCollectAssets)
{
if (collectAssetInfo.CollectorType == ECollectorType.DependAssetCollector)
{
if (IsRemoveDependAsset(allCollectAssets, collectAssetInfo.AssetPath))
removeDependList.Add(collectAssetInfo);
}
}
foreach (var removeValue in removeDependList)
{
allCollectAssets.Remove(removeValue);
}
// 4. 录入所有收集器收集的资源
foreach (var collectAssetInfo in allCollectAssets)
{
if (buildAssetDic.ContainsKey(collectAssetInfo.AssetPath) == false)
{
var buildAssetInfo = new BuildAssetInfo(
collectAssetInfo.CollectorType, collectAssetInfo.BundleName,
collectAssetInfo.Address, collectAssetInfo.AssetPath, collectAssetInfo.IsRawAsset);
buildAssetInfo.AddAssetTags(collectAssetInfo.AssetTags);
buildAssetInfo.AddBundleTags(collectAssetInfo.AssetTags);
buildAssetDic.Add(collectAssetInfo.AssetPath, buildAssetInfo);
}
else
{
throw new Exception($"Should never get here !");
}
}
// 5. 录入所有收集资源的依赖资源
foreach (var collectAssetInfo in allCollectAssets)
{
string collectAssetBundleName = collectAssetInfo.BundleName;
foreach (var dependAssetPath in collectAssetInfo.DependAssets)
{
if (buildAssetDic.ContainsKey(dependAssetPath))
{
buildAssetDic[dependAssetPath].AddBundleTags(collectAssetInfo.AssetTags);
buildAssetDic[dependAssetPath].AddReferenceBundleName(collectAssetBundleName);
}
else
{
var buildAssetInfo = new BuildAssetInfo(dependAssetPath);
buildAssetInfo.AddBundleTags(collectAssetInfo.AssetTags);
buildAssetInfo.AddReferenceBundleName(collectAssetBundleName);
buildAssetDic.Add(dependAssetPath, buildAssetInfo);
}
}
}
// 6. 填充所有收集资源的依赖列表
foreach (var collectAssetInfo in allCollectAssets)
{
var dependAssetInfos = new List<BuildAssetInfo>(collectAssetInfo.DependAssets.Count);
foreach (var dependAssetPath in collectAssetInfo.DependAssets)
{
if (buildAssetDic.TryGetValue(dependAssetPath, out BuildAssetInfo value))
dependAssetInfos.Add(value);
else
throw new Exception("Should never get here !");
}
buildAssetDic[collectAssetInfo.AssetPath].SetAllDependAssetInfos(dependAssetInfos);
}
// 7. 记录关键信息
BuildMapContext context = new BuildMapContext();
context.AssetFileCount = buildAssetDic.Count;
context.EnableAddressable = buildResult.Command.EnableAddressable;
context.UniqueBundleName = buildResult.Command.UniqueBundleName;
context.ShadersBundleName = buildResult.ShadersBundleName;
// 8. 计算共享的资源包名
var command = buildResult.Command;
foreach (KeyValuePair<string, BuildAssetInfo> pair in buildAssetDic)
{
pair.Value.CalculateShareBundleName(command.UniqueBundleName, command.PackageName, buildResult.ShadersBundleName);
}
// 9. 移除不参与构建的资源
List<BuildAssetInfo> removeBuildList = new List<BuildAssetInfo>();
foreach (KeyValuePair<string, BuildAssetInfo> pair in buildAssetDic)
{
var buildAssetInfo = pair.Value;
if (buildAssetInfo.HasBundleName() == false)
removeBuildList.Add(buildAssetInfo);
}
foreach (var removeValue in removeBuildList)
{
buildAssetDic.Remove(removeValue.AssetPath);
}
// 10. 构建资源包
var allBuildinAssets = buildAssetDic.Values.ToList();
if (allBuildinAssets.Count == 0)
throw new Exception("构建的资源列表不能为空");
foreach (var assetInfo in allBuildinAssets)
{
context.PackAsset(assetInfo);
}
return context;
}
private static bool IsRemoveDependAsset(List<CollectAssetInfo> allCollectAssets, string dependAssetPath)
{
foreach (var collectAssetInfo in allCollectAssets)
{
var collectorType = collectAssetInfo.CollectorType;
if (collectorType == ECollectorType.MainAssetCollector || collectorType == ECollectorType.StaticAssetCollector)
{
if (collectAssetInfo.DependAssets.Contains(dependAssetPath))
return false;
}
}
BuildRunner.Log($"发现未被依赖的资源并自动移除 : {dependAssetPath}");
return true;
}
}
}

View File

@@ -67,6 +67,11 @@ namespace YooAsset.Editor
public string PackageVersion; public string PackageVersion;
/// <summary>
/// 是否显示普通日志
/// </summary>
public bool EnableLog = true;
/// <summary> /// <summary>
/// 验证构建结果 /// 验证构建结果
/// </summary> /// </summary>

View File

@@ -7,8 +7,6 @@ namespace YooAsset.Editor
{ {
public class BuildParametersContext : IContextObject public class BuildParametersContext : IContextObject
{ {
private readonly System.Diagnostics.Stopwatch _buildWatch = new System.Diagnostics.Stopwatch();
private string _pipelineOutputDirectory = string.Empty; private string _pipelineOutputDirectory = string.Empty;
private string _packageOutputDirectory = string.Empty; private string _packageOutputDirectory = string.Empty;
@@ -117,22 +115,5 @@ namespace YooAsset.Editor
return buildParams; return buildParams;
} }
/// <summary>
/// 获取构建的耗时(单位:秒)
/// </summary>
public float GetBuildingSeconds()
{
float seconds = _buildWatch.ElapsedMilliseconds / 1000f;
return seconds;
}
public void BeginWatch()
{
_buildWatch.Start();
}
public void StopWatch()
{
_buildWatch.Stop();
}
} }
} }

View File

@@ -48,6 +48,11 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public string[] Tags; public string[] Tags;
/// <summary>
/// 引用该资源包的ID列表
/// </summary>
public int[] ReferenceIDs;
/// <summary> /// <summary>
/// 获取资源分类标签的字符串 /// 获取资源分类标签的字符串
/// </summary> /// </summary>

View File

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

View File

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

View File

@@ -2,13 +2,19 @@
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using System.Diagnostics;
using UnityEngine; using UnityEngine;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
public class BuildRunner public class BuildRunner
{ {
public static bool EnableLog = true; private static Stopwatch _buildWatch;
/// <summary>
/// 总耗时
/// </summary>
public static int TotalSeconds = 0;
/// <summary> /// <summary>
/// 执行构建流程 /// 执行构建流程
@@ -23,17 +29,26 @@ namespace YooAsset.Editor
BuildResult buildResult = new BuildResult(); BuildResult buildResult = new BuildResult();
buildResult.Success = true; buildResult.Success = true;
TotalSeconds = 0;
for (int i = 0; i < pipeline.Count; i++) for (int i = 0; i < pipeline.Count; i++)
{ {
IBuildTask task = pipeline[i]; IBuildTask task = pipeline[i];
try try
{ {
_buildWatch = Stopwatch.StartNew();
var taskAttribute = task.GetType().GetCustomAttribute<TaskAttribute>(); var taskAttribute = task.GetType().GetCustomAttribute<TaskAttribute>();
Log($"---------------------------------------->{taskAttribute.Desc}<---------------------------------------"); BuildLogger.Log($"---------------------------------------->{taskAttribute.Desc}<---------------------------------------");
task.Run(context); task.Run(context);
_buildWatch.Stop();
// 统计耗时
int seconds = GetBuildSeconds();
TotalSeconds += seconds;
BuildLogger.Log($"{taskAttribute.Desc}耗时:{seconds}秒");
} }
catch (Exception e) catch (Exception e)
{ {
EditorTools.ClearProgressBar();
buildResult.FailedTask = task.GetType().Name; buildResult.FailedTask = task.GetType().Name;
buildResult.FailedInfo = e.ToString(); buildResult.FailedInfo = e.ToString();
buildResult.Success = false; buildResult.Success = false;
@@ -42,26 +57,14 @@ namespace YooAsset.Editor
} }
// 返回运行结果 // 返回运行结果
BuildLogger.Log($"构建过程总计耗时:{TotalSeconds}秒");
return buildResult; return buildResult;
} }
/// <summary> private static int GetBuildSeconds()
/// 日志输出
/// </summary>
public static void Log(string info)
{ {
if (EnableLog) float seconds = _buildWatch.ElapsedMilliseconds / 1000f;
{ return (int)seconds;
UnityEngine.Debug.Log(info);
}
}
/// <summary>
/// 日志输出
/// </summary>
public static void Info(string info)
{
UnityEngine.Debug.Log(info);
} }
} }
} }

View File

@@ -41,7 +41,7 @@ namespace YooAsset.Editor
throw new Exception("构建过程中发生严重错误!请查阅上下文日志!"); throw new Exception("构建过程中发生严重错误!请查阅上下文日志!");
} }
BuildRunner.Log("Unity引擎打包成功"); BuildLogger.Log("Unity引擎打包成功");
BuildResultContext buildResultContext = new BuildResultContext(); BuildResultContext buildResultContext = new BuildResultContext();
buildResultContext.UnityManifest = buildResults; buildResultContext.UnityManifest = buildResults;
context.SetContextObject(buildResultContext); context.SetContextObject(buildResultContext);

View File

@@ -40,7 +40,16 @@ namespace YooAsset.Editor
throw new Exception($"构建过程中发生错误 : {exitCode}"); throw new Exception($"构建过程中发生错误 : {exitCode}");
} }
BuildRunner.Log("Unity引擎打包成功"); // 创建着色器信息
// 说明:解决因为着色器资源包导致验证失败。
// 例如:当项目里没有着色器,如果有依赖内置着色器就会验证失败。
string shadersBundleName = buildMapContext.ShadersBundleName;
if (buildResults.BundleInfos.ContainsKey(shadersBundleName))
{
buildMapContext.CreateShadersBundleInfo(shadersBundleName);
}
BuildLogger.Log("Unity引擎打包成功");
BuildResultContext buildResultContext = new BuildResultContext(); BuildResultContext buildResultContext = new BuildResultContext();
buildResultContext.Results = buildResults; buildResultContext.Results = buildResults;
context.SetContextObject(buildResultContext); context.SetContextObject(buildResultContext);

View File

@@ -94,7 +94,7 @@ namespace YooAsset.Editor
// 刷新目录 // 刷新目录
AssetDatabase.Refresh(); AssetDatabase.Refresh();
BuildRunner.Log($"内置文件拷贝完成:{streamingAssetsDirectory}"); BuildLogger.Log($"内置文件拷贝完成:{streamingAssetsDirectory}");
} }
} }
} }

View File

@@ -27,7 +27,7 @@ namespace YooAsset.Editor
private void CopyRawBundle(BuildMapContext buildMapContext, BuildParametersContext buildParametersContext) private void CopyRawBundle(BuildMapContext buildMapContext, BuildParametersContext buildParametersContext)
{ {
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory(); string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
foreach (var bundleInfo in buildMapContext.BundleInfos) foreach (var bundleInfo in buildMapContext.Collection)
{ {
if (bundleInfo.IsRawFile) if (bundleInfo.IsRawFile)
{ {

View File

@@ -67,7 +67,7 @@ namespace YooAsset.Editor
if (buildParameters.BuildMode != EBuildMode.SimulateBuild) if (buildParameters.BuildMode != EBuildMode.SimulateBuild)
{ {
var buildResultContext = context.GetContextObject<TaskBuilding.BuildResultContext>(); var buildResultContext = context.GetContextObject<TaskBuilding.BuildResultContext>();
UpdateBuiltinPipelineReference(patchManifest, buildResultContext, buildMapContext); UpdateBuiltinPipelineReference(patchManifest, buildResultContext);
} }
} }
@@ -76,7 +76,7 @@ namespace YooAsset.Editor
string fileName = YooAssetSettingsData.GetManifestJsonFileName(buildParameters.PackageName, buildParameters.PackageVersion); string fileName = YooAssetSettingsData.GetManifestJsonFileName(buildParameters.PackageName, buildParameters.PackageVersion);
string filePath = $"{packageOutputDirectory}/{fileName}"; string filePath = $"{packageOutputDirectory}/{fileName}";
PatchManifestTools.SerializeToJson(filePath, patchManifest); PatchManifestTools.SerializeToJson(filePath, patchManifest);
BuildRunner.Log($"创建补丁清单文件:{filePath}"); BuildLogger.Log($"创建补丁清单文件:{filePath}");
} }
// 创建补丁清单二进制文件 // 创建补丁清单二进制文件
@@ -86,7 +86,7 @@ namespace YooAsset.Editor
string filePath = $"{packageOutputDirectory}/{fileName}"; string filePath = $"{packageOutputDirectory}/{fileName}";
PatchManifestTools.SerializeToBinary(filePath, patchManifest); PatchManifestTools.SerializeToBinary(filePath, patchManifest);
packageHash = HashUtility.FileMD5(filePath); packageHash = HashUtility.FileMD5(filePath);
BuildRunner.Log($"创建补丁清单文件:{filePath}"); BuildLogger.Log($"创建补丁清单文件:{filePath}");
PatchManifestContext patchManifestContext = new PatchManifestContext(); PatchManifestContext patchManifestContext = new PatchManifestContext();
byte[] bytesData = FileUtility.ReadAllBytes(filePath); byte[] bytesData = FileUtility.ReadAllBytes(filePath);
@@ -99,7 +99,7 @@ namespace YooAsset.Editor
string fileName = YooAssetSettingsData.GetPackageHashFileName(buildParameters.PackageName, buildParameters.PackageVersion); string fileName = YooAssetSettingsData.GetPackageHashFileName(buildParameters.PackageName, buildParameters.PackageVersion);
string filePath = $"{packageOutputDirectory}/{fileName}"; string filePath = $"{packageOutputDirectory}/{fileName}";
FileUtility.CreateFile(filePath, packageHash); FileUtility.CreateFile(filePath, packageHash);
BuildRunner.Log($"创建补丁清单哈希文件:{filePath}"); BuildLogger.Log($"创建补丁清单哈希文件:{filePath}");
} }
// 创建补丁清单版本文件 // 创建补丁清单版本文件
@@ -107,7 +107,7 @@ namespace YooAsset.Editor
string fileName = YooAssetSettingsData.GetPackageVersionFileName(buildParameters.PackageName); string fileName = YooAssetSettingsData.GetPackageVersionFileName(buildParameters.PackageName);
string filePath = $"{packageOutputDirectory}/{fileName}"; string filePath = $"{packageOutputDirectory}/{fileName}";
FileUtility.CreateFile(filePath, buildParameters.PackageVersion); FileUtility.CreateFile(filePath, buildParameters.PackageVersion);
BuildRunner.Log($"创建补丁清单版本文件:{filePath}"); BuildLogger.Log($"创建补丁清单版本文件:{filePath}");
} }
} }
@@ -119,7 +119,7 @@ namespace YooAsset.Editor
var buildMapContext = context.GetContextObject<BuildMapContext>(); var buildMapContext = context.GetContextObject<BuildMapContext>();
List<PatchBundle> result = new List<PatchBundle>(1000); List<PatchBundle> result = new List<PatchBundle>(1000);
foreach (var bundleInfo in buildMapContext.BundleInfos) foreach (var bundleInfo in buildMapContext.Collection)
{ {
var patchBundle = bundleInfo.CreatePatchBundle(); var patchBundle = bundleInfo.CreatePatchBundle();
result.Add(patchBundle); result.Add(patchBundle);
@@ -135,7 +135,7 @@ namespace YooAsset.Editor
var buildMapContext = context.GetContextObject<BuildMapContext>(); var buildMapContext = context.GetContextObject<BuildMapContext>();
List<PatchAsset> result = new List<PatchAsset>(1000); List<PatchAsset> result = new List<PatchAsset>(1000);
foreach (var bundleInfo in buildMapContext.BundleInfos) foreach (var bundleInfo in buildMapContext.Collection)
{ {
var assetInfos = bundleInfo.GetAllPatchAssetInfos(); var assetInfos = bundleInfo.GetAllPatchAssetInfos();
foreach (var assetInfo in assetInfos) foreach (var assetInfo in assetInfos)
@@ -231,30 +231,108 @@ namespace YooAsset.Editor
return result; return result;
} }
/// <summary> #region
/// 更新资源包之间的引用关系 private readonly Dictionary<string, int> _cachedBundleID = new Dictionary<string, int>(10000);
/// </summary> private readonly Dictionary<string, string[]> _cachedBundleDepends = new Dictionary<string, string[]>(10000);
private void UpdateScriptPipelineReference(PatchManifest patchManifest, TaskBuilding_SBP.BuildResultContext buildResultContext) private void UpdateScriptPipelineReference(PatchManifest patchManifest, TaskBuilding_SBP.BuildResultContext buildResultContext)
{ {
int progressValue;
int totalCount = patchManifest.BundleList.Count;
// 缓存资源包ID
_cachedBundleID.Clear();
progressValue = 0;
foreach (var patchBundle in patchManifest.BundleList) foreach (var patchBundle in patchManifest.BundleList)
{ {
patchBundle.ReferenceIDs = GetScriptPipelineRefrenceIDs(patchManifest, patchBundle, buildResultContext); int bundleID = GetAssetBundleID(patchBundle.BundleName, patchManifest);
} _cachedBundleID.Add(patchBundle.BundleName, bundleID);
} EditorTools.DisplayProgressBar("缓存资源包索引", ++progressValue, totalCount);
private int[] GetScriptPipelineRefrenceIDs(PatchManifest patchManifest, PatchBundle patchBundle, TaskBuilding_SBP.BuildResultContext buildResultContext)
{
if (buildResultContext.Results.BundleInfos.TryGetValue(patchBundle.BundleName, out var details) == false)
{
throw new Exception("Should never get here !");
} }
EditorTools.ClearProgressBar();
List<string> referenceList = new List<string>(); // 缓存资源包依赖
foreach (var keyValuePair in buildResultContext.Results.BundleInfos) _cachedBundleDepends.Clear();
progressValue = 0;
foreach (var patchBundle in patchManifest.BundleList)
{ {
string bundleName = keyValuePair.Key; if (patchBundle.IsRawFile)
if (bundleName == patchBundle.BundleName) {
_cachedBundleDepends.Add(patchBundle.BundleName, new string[] { });
continue; continue;
if (keyValuePair.Value.Dependencies.Contains(patchBundle.BundleName)) }
if (buildResultContext.Results.BundleInfos.ContainsKey(patchBundle.BundleName) == false)
throw new Exception($"Not found bundle in SBP build results : {patchBundle.BundleName}");
var depends = buildResultContext.Results.BundleInfos[patchBundle.BundleName].Dependencies;
_cachedBundleDepends.Add(patchBundle.BundleName, depends);
EditorTools.DisplayProgressBar("缓存资源包依赖列表", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
// 计算资源包引用列表
foreach (var patchBundle in patchManifest.BundleList)
{
patchBundle.ReferenceIDs = GetBundleRefrenceIDs(patchManifest, patchBundle);
EditorTools.DisplayProgressBar("计算资源包引用关系", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
}
private void UpdateBuiltinPipelineReference(PatchManifest patchManifest, TaskBuilding.BuildResultContext buildResultContext)
{
int progressValue;
int totalCount = patchManifest.BundleList.Count;
// 缓存资源包ID
_cachedBundleID.Clear();
progressValue = 0;
foreach (var patchBundle in patchManifest.BundleList)
{
int bundleID = GetAssetBundleID(patchBundle.BundleName, patchManifest);
_cachedBundleID.Add(patchBundle.BundleName, bundleID);
EditorTools.DisplayProgressBar("缓存资源包索引", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
// 缓存资源包依赖
_cachedBundleDepends.Clear();
progressValue = 0;
foreach (var patchBundle in patchManifest.BundleList)
{
if (patchBundle.IsRawFile)
{
_cachedBundleDepends.Add(patchBundle.BundleName, new string[] { } );
continue;
}
var depends = buildResultContext.UnityManifest.GetDirectDependencies(patchBundle.BundleName);
_cachedBundleDepends.Add(patchBundle.BundleName, depends);
EditorTools.DisplayProgressBar("缓存资源包依赖列表", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
// 计算资源包引用列表
progressValue = 0;
foreach (var patchBundle in patchManifest.BundleList)
{
patchBundle.ReferenceIDs = GetBundleRefrenceIDs(patchManifest, patchBundle);
EditorTools.DisplayProgressBar("计算资源包引用关系", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
}
private int[] GetBundleRefrenceIDs(PatchManifest patchManifest, PatchBundle targetBundle)
{
List<string> referenceList = new List<string>();
foreach (var patchBundle in patchManifest.BundleList)
{
string bundleName = patchBundle.BundleName;
if (bundleName == targetBundle.BundleName)
continue;
string[] dependencies = GetCachedBundleDepends(bundleName);
if (dependencies.Contains(targetBundle.BundleName))
{ {
referenceList.Add(bundleName); referenceList.Add(bundleName);
} }
@@ -263,46 +341,28 @@ namespace YooAsset.Editor
List<int> result = new List<int>(); List<int> result = new List<int>();
foreach (var bundleName in referenceList) foreach (var bundleName in referenceList)
{ {
int bundleID = GetAssetBundleID(bundleName, patchManifest); int bundleID = GetCachedBundleID(bundleName);
if (result.Contains(bundleID) == false) if (result.Contains(bundleID) == false)
result.Add(bundleID); result.Add(bundleID);
} }
return result.ToArray(); return result.ToArray();
} }
private int GetCachedBundleID(string bundleName)
/// <summary>
/// 更新资源包之间的引用关系
/// </summary>
private void UpdateBuiltinPipelineReference(PatchManifest patchManifest, TaskBuilding.BuildResultContext buildResultContext, BuildMapContext buildMapContext)
{ {
foreach (var patchBundle in patchManifest.BundleList) if (_cachedBundleID.TryGetValue(bundleName, out int value) == false)
{ {
patchBundle.ReferenceIDs = GetBuiltinPipelineRefrenceIDs(patchManifest, patchBundle, buildResultContext, buildMapContext); throw new Exception($"Not found cached bundle ID : {bundleName}");
} }
return value;
} }
private int[] GetBuiltinPipelineRefrenceIDs(PatchManifest patchManifest, PatchBundle patchBundle, TaskBuilding.BuildResultContext buildResultContext, BuildMapContext buildMapContext) private string[] GetCachedBundleDepends(string bundleName)
{ {
List<string> referenceList = new List<string>(); if (_cachedBundleDepends.TryGetValue(bundleName, out string[] value) == false)
foreach (var bundleInfo in buildMapContext.BundleInfos)
{ {
string bundleName = bundleInfo.BundleName; throw new Exception($"Not found cached bundle depends : {bundleName}");
if (bundleName == patchBundle.BundleName)
continue;
string[] dependencies = buildResultContext.UnityManifest.GetAllDependencies(bundleName);
if (dependencies.Contains(patchBundle.BundleName))
{
referenceList.Add(bundleName);
}
} }
return value;
List<int> result = new List<int>();
foreach (var bundleName in referenceList)
{
int bundleID = GetAssetBundleID(bundleName, patchManifest);
if (result.Contains(bundleID) == false)
result.Add(bundleID);
}
return result.ToArray();
} }
#endregion
} }
} }

View File

@@ -25,7 +25,7 @@ namespace YooAsset.Editor
var buildParameters = buildParametersContext.Parameters; var buildParameters = buildParametersContext.Parameters;
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory(); string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
string packageOutputDirectory = buildParametersContext.GetPackageOutputDirectory(); string packageOutputDirectory = buildParametersContext.GetPackageOutputDirectory();
BuildRunner.Log($"开始拷贝补丁文件到补丁包目录:{packageOutputDirectory}"); BuildLogger.Log($"开始拷贝补丁文件到补丁包目录:{packageOutputDirectory}");
if (buildParameters.BuildPipeline == EBuildPipeline.ScriptableBuildPipeline) if (buildParameters.BuildPipeline == EBuildPipeline.ScriptableBuildPipeline)
{ {
@@ -67,8 +67,8 @@ namespace YooAsset.Editor
// 拷贝所有补丁文件 // 拷贝所有补丁文件
int progressValue = 0; int progressValue = 0;
int patchFileTotalCount = buildMapContext.BundleInfos.Count; int patchFileTotalCount = buildMapContext.Collection.Count;
foreach (var bundleInfo in buildMapContext.BundleInfos) foreach (var bundleInfo in buildMapContext.Collection)
{ {
EditorTools.CopyFile(bundleInfo.PatchInfo.BuildOutputFilePath, bundleInfo.PatchInfo.PatchOutputFilePath, true); EditorTools.CopyFile(bundleInfo.PatchInfo.BuildOutputFilePath, bundleInfo.PatchInfo.PatchOutputFilePath, true);
EditorTools.DisplayProgressBar("拷贝补丁文件", ++progressValue, patchFileTotalCount); EditorTools.DisplayProgressBar("拷贝补丁文件", ++progressValue, patchFileTotalCount);

View File

@@ -13,16 +13,12 @@ namespace YooAsset.Editor
var buildParameters = context.GetContextObject<BuildParametersContext>(); var buildParameters = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>(); var buildMapContext = context.GetContextObject<BuildMapContext>();
var patchManifestContext = context.GetContextObject<PatchManifestContext>(); var patchManifestContext = context.GetContextObject<PatchManifestContext>();
buildParameters.StopWatch();
var buildMode = buildParameters.Parameters.BuildMode; var buildMode = buildParameters.Parameters.BuildMode;
if (buildMode != EBuildMode.SimulateBuild) if (buildMode != EBuildMode.SimulateBuild)
{ {
CreateReportFile(buildParameters, buildMapContext, patchManifestContext); CreateReportFile(buildParameters, buildMapContext, patchManifestContext);
} }
float buildSeconds = buildParameters.GetBuildingSeconds();
BuildRunner.Info($"Build time consuming {buildSeconds} seconds.");
} }
private void CreateReportFile(BuildParametersContext buildParametersContext, BuildMapContext buildMapContext, PatchManifestContext patchManifestContext) private void CreateReportFile(BuildParametersContext buildParametersContext, BuildMapContext buildMapContext, PatchManifestContext patchManifestContext)
@@ -42,7 +38,7 @@ namespace YooAsset.Editor
#endif #endif
buildReport.Summary.UnityVersion = UnityEngine.Application.unityVersion; buildReport.Summary.UnityVersion = UnityEngine.Application.unityVersion;
buildReport.Summary.BuildDate = DateTime.Now.ToString(); buildReport.Summary.BuildDate = DateTime.Now.ToString();
buildReport.Summary.BuildSeconds = (int)buildParametersContext.GetBuildingSeconds(); buildReport.Summary.BuildSeconds = BuildRunner.TotalSeconds;
buildReport.Summary.BuildTarget = buildParameters.BuildTarget; buildReport.Summary.BuildTarget = buildParameters.BuildTarget;
buildReport.Summary.BuildPipeline = buildParameters.BuildPipeline; buildReport.Summary.BuildPipeline = buildParameters.BuildPipeline;
buildReport.Summary.BuildMode = buildParameters.BuildMode; buildReport.Summary.BuildMode = buildParameters.BuildMode;
@@ -98,6 +94,7 @@ namespace YooAsset.Editor
reportBundleInfo.FileCRC = patchBundle.FileCRC; reportBundleInfo.FileCRC = patchBundle.FileCRC;
reportBundleInfo.FileSize = patchBundle.FileSize; reportBundleInfo.FileSize = patchBundle.FileSize;
reportBundleInfo.Tags = patchBundle.Tags; reportBundleInfo.Tags = patchBundle.Tags;
reportBundleInfo.ReferenceIDs = patchBundle.ReferenceIDs;
reportBundleInfo.IsRawFile = patchBundle.IsRawFile; reportBundleInfo.IsRawFile = patchBundle.IsRawFile;
reportBundleInfo.LoadMethod = (EBundleLoadMethod)patchBundle.LoadMethod; reportBundleInfo.LoadMethod = (EBundleLoadMethod)patchBundle.LoadMethod;
buildReport.BundleInfos.Add(reportBundleInfo); buildReport.BundleInfos.Add(reportBundleInfo);
@@ -107,7 +104,7 @@ namespace YooAsset.Editor
string fileName = YooAssetSettingsData.GetReportFileName(buildParameters.PackageName, buildParameters.PackageVersion); string fileName = YooAssetSettingsData.GetReportFileName(buildParameters.PackageName, buildParameters.PackageVersion);
string filePath = $"{packageOutputDirectory}/{fileName}"; string filePath = $"{packageOutputDirectory}/{fileName}";
BuildReport.Serialize(filePath, buildReport); BuildReport.Serialize(filePath, buildReport);
BuildRunner.Log($"资源构建报告文件创建完成:{filePath}"); BuildLogger.Log($"资源构建报告文件创建完成:{filePath}");
} }
/// <summary> /// <summary>
@@ -130,7 +127,7 @@ namespace YooAsset.Editor
private List<string> GetDependAssets(BuildMapContext buildMapContext, string bundleName, string assetPath) private List<string> GetDependAssets(BuildMapContext buildMapContext, string bundleName, string assetPath)
{ {
List<string> result = new List<string>(); List<string> result = new List<string>();
if (buildMapContext.TryGetBundleInfo(bundleName, out BuildBundleInfo bundleInfo)) var bundleInfo = buildMapContext.GetBundleInfo(bundleName);
{ {
BuildAssetInfo findAssetInfo = null; BuildAssetInfo findAssetInfo = null;
foreach (var buildinAsset in bundleInfo.BuildinAssets) foreach (var buildinAsset in bundleInfo.BuildinAssets)
@@ -150,10 +147,6 @@ namespace YooAsset.Editor
result.Add(dependAssetInfo.AssetPath); result.Add(dependAssetInfo.AssetPath);
} }
} }
else
{
throw new Exception($"Not found bundle : {bundleName}");
}
return result; return result;
} }

View File

@@ -27,17 +27,16 @@ namespace YooAsset.Editor
private void EncryptingBundleFiles(BuildParametersContext buildParametersContext, BuildMapContext buildMapContext) private void EncryptingBundleFiles(BuildParametersContext buildParametersContext, BuildMapContext buildMapContext)
{ {
var encryptionServices = buildParametersContext.Parameters.EncryptionServices; var encryptionServices = buildParametersContext.Parameters.EncryptionServices;
// 如果没有设置加密类
if (encryptionServices == null) if (encryptionServices == null)
return; return;
if (encryptionServices.GetType() == typeof(EncryptionNone))
return;
int progressValue = 0; int progressValue = 0;
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory(); string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
foreach (var bundleInfo in buildMapContext.BundleInfos) foreach (var bundleInfo in buildMapContext.Collection)
{ {
bundleInfo.LoadMethod = EBundleLoadMethod.Normal;
EncryptFileInfo fileInfo = new EncryptFileInfo(); EncryptFileInfo fileInfo = new EncryptFileInfo();
fileInfo.BundleName = bundleInfo.BundleName; fileInfo.BundleName = bundleInfo.BundleName;
fileInfo.FilePath = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}"; fileInfo.FilePath = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}";
@@ -48,7 +47,7 @@ namespace YooAsset.Editor
// 注意:原生文件不支持加密 // 注意:原生文件不支持加密
if (bundleInfo.IsRawFile) if (bundleInfo.IsRawFile)
{ {
UnityEngine.Debug.LogWarning($"Encryption not support raw file : {bundleInfo.BundleName}"); BuildLogger.Warning($"Encryption not support raw file : {bundleInfo.BundleName}");
continue; continue;
} }
@@ -56,11 +55,11 @@ namespace YooAsset.Editor
FileUtility.CreateFile(filePath, encryptResult.EncryptedData); FileUtility.CreateFile(filePath, encryptResult.EncryptedData);
bundleInfo.EncryptedFilePath = filePath; bundleInfo.EncryptedFilePath = filePath;
bundleInfo.LoadMethod = encryptResult.LoadMethod; bundleInfo.LoadMethod = encryptResult.LoadMethod;
BuildRunner.Log($"Bundle文件加密完成{filePath}"); BuildLogger.Log($"Bundle文件加密完成{filePath}");
} }
// 进度条 // 进度条
EditorTools.DisplayProgressBar("加密资源包", ++progressValue, buildMapContext.BundleInfos.Count); EditorTools.DisplayProgressBar("加密资源包", ++progressValue, buildMapContext.Collection.Count);
} }
EditorTools.ClearProgressBar(); EditorTools.ClearProgressBar();
} }

View File

@@ -13,20 +13,155 @@ namespace YooAsset.Editor
void IBuildTask.Run(BuildContext context) void IBuildTask.Run(BuildContext context)
{ {
var buildParametersContext = context.GetContextObject<BuildParametersContext>(); var buildParametersContext = context.GetContextObject<BuildParametersContext>();
var buildMapContext = BuildMapCreater.CreateBuildMap(buildParametersContext.Parameters.BuildMode, buildParametersContext.Parameters.PackageName); var buildMapContext = CreateBuildMap(buildParametersContext.Parameters.BuildMode, buildParametersContext.Parameters.PackageName);
context.SetContextObject(buildMapContext); context.SetContextObject(buildMapContext);
BuildRunner.Log("构建内容准备完毕!"); BuildLogger.Log("构建内容准备完毕!");
// 检测构建结果 // 检测构建结果
CheckBuildMapContent(buildMapContext); CheckBuildMapContent(buildMapContext);
} }
/// <summary>
/// 资源构建上下文
/// </summary>
public BuildMapContext CreateBuildMap(EBuildMode buildMode, string packageName)
{
Dictionary<string, BuildAssetInfo> buildAssetInfoDic = new Dictionary<string, BuildAssetInfo>(1000);
// 1. 检测配置合法性
AssetBundleCollectorSettingData.Setting.CheckConfigError();
// 2. 获取所有收集器收集的资源
var collectResult = AssetBundleCollectorSettingData.Setting.GetPackageAssets(buildMode, packageName);
List<CollectAssetInfo> collectAssetInfos = collectResult.CollectAssets;
// 3. 剔除未被引用的依赖项资源
List<CollectAssetInfo> removeDependList = new List<CollectAssetInfo>();
foreach (var collectAssetInfo in collectAssetInfos)
{
if (collectAssetInfo.CollectorType == ECollectorType.DependAssetCollector)
{
if (IsRemoveDependAsset(collectAssetInfos, collectAssetInfo.AssetPath))
removeDependList.Add(collectAssetInfo);
}
}
foreach (var removeValue in removeDependList)
{
collectAssetInfos.Remove(removeValue);
}
// 4. 录入所有收集器收集的资源
foreach (var collectAssetInfo in collectAssetInfos)
{
if (buildAssetInfoDic.ContainsKey(collectAssetInfo.AssetPath) == false)
{
var buildAssetInfo = new BuildAssetInfo(
collectAssetInfo.CollectorType, collectAssetInfo.BundleName,
collectAssetInfo.Address, collectAssetInfo.AssetPath, collectAssetInfo.IsRawAsset);
buildAssetInfo.AddAssetTags(collectAssetInfo.AssetTags);
buildAssetInfo.AddBundleTags(collectAssetInfo.AssetTags);
buildAssetInfoDic.Add(collectAssetInfo.AssetPath, buildAssetInfo);
}
else
{
throw new Exception($"Should never get here !");
}
}
// 5. 录入所有收集资源的依赖资源
foreach (var collectAssetInfo in collectAssetInfos)
{
string collectAssetBundleName = collectAssetInfo.BundleName;
foreach (var dependAssetPath in collectAssetInfo.DependAssets)
{
if (buildAssetInfoDic.ContainsKey(dependAssetPath))
{
buildAssetInfoDic[dependAssetPath].AddBundleTags(collectAssetInfo.AssetTags);
buildAssetInfoDic[dependAssetPath].AddReferenceBundleName(collectAssetBundleName);
}
else
{
var buildAssetInfo = new BuildAssetInfo(dependAssetPath);
buildAssetInfo.AddBundleTags(collectAssetInfo.AssetTags);
buildAssetInfo.AddReferenceBundleName(collectAssetBundleName);
buildAssetInfoDic.Add(dependAssetPath, buildAssetInfo);
}
}
}
// 6. 填充所有收集资源的依赖列表
foreach (var collectAssetInfo in collectAssetInfos)
{
var dependAssetInfos = new List<BuildAssetInfo>(collectAssetInfo.DependAssets.Count);
foreach (var dependAssetPath in collectAssetInfo.DependAssets)
{
if (buildAssetInfoDic.TryGetValue(dependAssetPath, out BuildAssetInfo value))
dependAssetInfos.Add(value);
else
throw new Exception("Should never get here !");
}
buildAssetInfoDic[collectAssetInfo.AssetPath].SetAllDependAssetInfos(dependAssetInfos);
}
// 7. 记录关键信息
BuildMapContext context = new BuildMapContext();
context.AssetFileCount = buildAssetInfoDic.Count;
context.EnableAddressable = collectResult.Command.EnableAddressable;
context.UniqueBundleName = collectResult.Command.UniqueBundleName;
context.ShadersBundleName = collectResult.Command.ShadersBundleName;
// 8. 计算共享的资源包名
var command = collectResult.Command;
foreach (KeyValuePair<string, BuildAssetInfo> pair in buildAssetInfoDic)
{
pair.Value.CalculateShareBundleName(command.UniqueBundleName, command.PackageName, command.ShadersBundleName);
}
// 9. 移除不参与构建的资源
List<BuildAssetInfo> removeBuildList = new List<BuildAssetInfo>();
foreach (KeyValuePair<string, BuildAssetInfo> pair in buildAssetInfoDic)
{
var buildAssetInfo = pair.Value;
if (buildAssetInfo.HasBundleName() == false)
removeBuildList.Add(buildAssetInfo);
}
foreach (var removeValue in removeBuildList)
{
buildAssetInfoDic.Remove(removeValue.AssetPath);
}
// 10. 构建资源包
var allBuildinAssets = buildAssetInfoDic.Values.ToList();
if (allBuildinAssets.Count == 0)
throw new Exception("构建的资源列表不能为空");
foreach (var assetInfo in allBuildinAssets)
{
context.PackAsset(assetInfo);
}
return context;
}
private bool IsRemoveDependAsset(List<CollectAssetInfo> allCollectAssets, string dependAssetPath)
{
foreach (var collectAssetInfo in allCollectAssets)
{
var collectorType = collectAssetInfo.CollectorType;
if (collectorType == ECollectorType.MainAssetCollector || collectorType == ECollectorType.StaticAssetCollector)
{
if (collectAssetInfo.DependAssets.Contains(dependAssetPath))
return false;
}
}
BuildLogger.Log($"发现未被依赖的资源并自动移除 : {dependAssetPath}");
return true;
}
/// <summary> /// <summary>
/// 检测构建结果 /// 检测构建结果
/// </summary> /// </summary>
private void CheckBuildMapContent(BuildMapContext buildMapContext) private void CheckBuildMapContent(BuildMapContext buildMapContext)
{ {
foreach (var bundleInfo in buildMapContext.BundleInfos) foreach (var bundleInfo in buildMapContext.Collection)
{ {
// 注意:原生文件资源包只能包含一个原生文件 // 注意:原生文件资源包只能包含一个原生文件
bool isRawFile = bundleInfo.IsRawFile; bool isRawFile = bundleInfo.IsRawFile;

View File

@@ -12,8 +12,6 @@ namespace YooAsset.Editor
void IBuildTask.Run(BuildContext context) void IBuildTask.Run(BuildContext context)
{ {
var buildParametersContext = context.GetContextObject<BuildParametersContext>(); var buildParametersContext = context.GetContextObject<BuildParametersContext>();
buildParametersContext.BeginWatch();
var buildParameters = buildParametersContext.Parameters; var buildParameters = buildParametersContext.Parameters;
// 检测构建参数合法性 // 检测构建参数合法性
@@ -57,7 +55,7 @@ namespace YooAsset.Editor
string platformDirectory = $"{buildParameters.OutputRoot}/{buildParameters.PackageName}/{buildParameters.BuildTarget}"; string platformDirectory = $"{buildParameters.OutputRoot}/{buildParameters.PackageName}/{buildParameters.BuildTarget}";
if (EditorTools.DeleteDirectory(platformDirectory)) if (EditorTools.DeleteDirectory(platformDirectory))
{ {
BuildRunner.Log($"删除平台总目录:{platformDirectory}"); BuildLogger.Log($"删除平台总目录:{platformDirectory}");
} }
} }
@@ -65,7 +63,7 @@ namespace YooAsset.Editor
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory(); string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
if (EditorTools.CreateDirectory(pipelineOutputDirectory)) if (EditorTools.CreateDirectory(pipelineOutputDirectory))
{ {
BuildRunner.Log($"创建输出目录:{pipelineOutputDirectory}"); BuildLogger.Log($"创建输出目录:{pipelineOutputDirectory}");
} }
} }
} }

View File

@@ -6,8 +6,8 @@ using UnityEditor;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
[TaskAttribute("更新构建信息")] [TaskAttribute("更新补丁信息")]
public class TaskUpdateBuildInfo : IBuildTask public class TaskUpdatePatchInfo : IBuildTask
{ {
void IBuildTask.Run(BuildContext context) void IBuildTask.Run(BuildContext context)
{ {
@@ -18,7 +18,7 @@ namespace YooAsset.Editor
int outputNameStyle = (int)buildParametersContext.Parameters.OutputNameStyle; int outputNameStyle = (int)buildParametersContext.Parameters.OutputNameStyle;
// 1.检测路径长度 // 1.检测路径长度
foreach (var bundleInfo in buildMapContext.BundleInfos) foreach (var bundleInfo in buildMapContext.Collection)
{ {
// NOTE检测路径长度不要超过260字符。 // NOTE检测路径长度不要超过260字符。
string filePath = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}"; string filePath = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}";
@@ -27,7 +27,7 @@ namespace YooAsset.Editor
} }
// 2.更新构建输出的文件路径 // 2.更新构建输出的文件路径
foreach (var bundleInfo in buildMapContext.BundleInfos) foreach (var bundleInfo in buildMapContext.Collection)
{ {
if (bundleInfo.IsEncryptedFile) if (bundleInfo.IsEncryptedFile)
bundleInfo.PatchInfo.BuildOutputFilePath = bundleInfo.EncryptedFilePath; bundleInfo.PatchInfo.BuildOutputFilePath = bundleInfo.EncryptedFilePath;
@@ -36,7 +36,7 @@ namespace YooAsset.Editor
} }
// 3.更新文件其它信息 // 3.更新文件其它信息
foreach (var bundleInfo in buildMapContext.BundleInfos) foreach (var bundleInfo in buildMapContext.Collection)
{ {
string buildOutputFilePath = bundleInfo.PatchInfo.BuildOutputFilePath; string buildOutputFilePath = bundleInfo.PatchInfo.BuildOutputFilePath;
bundleInfo.PatchInfo.ContentHash = GetBundleContentHash(bundleInfo, context); bundleInfo.PatchInfo.ContentHash = GetBundleContentHash(bundleInfo, context);
@@ -46,7 +46,7 @@ namespace YooAsset.Editor
} }
// 4.更新补丁包输出的文件路径 // 4.更新补丁包输出的文件路径
foreach (var bundleInfo in buildMapContext.BundleInfos) foreach (var bundleInfo in buildMapContext.Collection)
{ {
string patchFileExtension = PatchManifestTools.GetRemoteBundleFileExtension(bundleInfo.BundleName); string patchFileExtension = PatchManifestTools.GetRemoteBundleFileExtension(bundleInfo.BundleName);
string patchFileName = PatchManifestTools.GetRemoteBundleFileName(outputNameStyle, bundleInfo.BundleName, patchFileExtension, bundleInfo.PatchInfo.PatchFileHash); string patchFileName = PatchManifestTools.GetRemoteBundleFileName(outputNameStyle, bundleInfo.BundleName, patchFileExtension, bundleInfo.PatchInfo.PatchFileHash);

View File

@@ -34,29 +34,29 @@ namespace YooAsset.Editor
{ {
var buildParametersContext = context.GetContextObject<BuildParametersContext>(); var buildParametersContext = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>(); var buildMapContext = context.GetContextObject<BuildMapContext>();
string[] buildedBundles = unityManifest.GetAllAssetBundles(); string[] unityCreateBundles = unityManifest.GetAllAssetBundles();
// 1. 过滤掉原生Bundle // 1. 过滤掉原生Bundle
string[] mapBundles = buildMapContext.BundleInfos.Where(t => t.IsRawFile == false).Select(t => t.BundleName).ToArray(); string[] mapBundles = buildMapContext.Collection.Where(t => t.IsRawFile == false).Select(t => t.BundleName).ToArray();
// 2. 验证Bundle // 2. 验证Bundle
List<string> exceptBundleList1 = buildedBundles.Except(mapBundles).ToList(); List<string> exceptBundleList1 = unityCreateBundles.Except(mapBundles).ToList();
if (exceptBundleList1.Count > 0) if (exceptBundleList1.Count > 0)
{ {
foreach (var exceptBundle in exceptBundleList1) foreach (var exceptBundle in exceptBundleList1)
{ {
Debug.LogWarning($"差异资源包: {exceptBundle}"); BuildLogger.Warning($"差异资源包: {exceptBundle}");
} }
throw new System.Exception("存在差异资源包!请查看警告信息!"); throw new System.Exception("存在差异资源包!请查看警告信息!");
} }
// 3. 验证Bundle // 3. 验证Bundle
List<string> exceptBundleList2 = mapBundles.Except(buildedBundles).ToList(); List<string> exceptBundleList2 = mapBundles.Except(unityCreateBundles).ToList();
if (exceptBundleList2.Count > 0) if (exceptBundleList2.Count > 0)
{ {
foreach (var exceptBundle in exceptBundleList2) foreach (var exceptBundle in exceptBundleList2)
{ {
Debug.LogWarning($"差异资源包: {exceptBundle}"); BuildLogger.Warning($"差异资源包: {exceptBundle}");
} }
throw new System.Exception("存在差异资源包!请查看警告信息!"); throw new System.Exception("存在差异资源包!请查看警告信息!");
} }
@@ -76,16 +76,16 @@ namespace YooAsset.Editor
string[] mapAssetPaths = buildMapContext.GetBuildinAssetPaths(buildedBundle); string[] mapAssetPaths = buildMapContext.GetBuildinAssetPaths(buildedBundle);
if (mapAssetPaths.Length != buildedAssetPaths.Length) if (mapAssetPaths.Length != buildedAssetPaths.Length)
{ {
Debug.LogWarning($"构建的Bundle文件内的资源对象数量和预期不匹配 : {buildedBundle}"); BuildLogger.Warning($"构建的Bundle文件内的资源对象数量和预期不匹配 : {buildedBundle}");
var exceptAssetList1 = mapAssetPaths.Except(buildedAssetPaths).ToList(); var exceptAssetList1 = mapAssetPaths.Except(buildedAssetPaths).ToList();
foreach (var excpetAsset in exceptAssetList1) foreach (var excpetAsset in exceptAssetList1)
{ {
Debug.LogWarning($"构建失败的资源对象路径为 : {excpetAsset}"); BuildLogger.Warning($"构建失败的资源对象路径为 : {excpetAsset}");
} }
var exceptAssetList2 = buildedAssetPaths.Except(mapAssetPaths).ToList(); var exceptAssetList2 = buildedAssetPaths.Except(mapAssetPaths).ToList();
foreach (var excpetAsset in exceptAssetList2) foreach (var excpetAsset in exceptAssetList2)
{ {
Debug.LogWarning($"构建失败的资源对象路径为 : {excpetAsset}"); BuildLogger.Warning($"构建失败的资源对象路径为 : {excpetAsset}");
} }
isPass = false; isPass = false;
continue; continue;
@@ -101,7 +101,7 @@ namespace YooAsset.Editor
} }
*/ */
BuildRunner.Log("构建结果验证成功!"); BuildLogger.Log("构建结果验证成功!");
} }
/// <summary> /// <summary>

View File

@@ -35,34 +35,34 @@ namespace YooAsset.Editor
{ {
var buildParameters = context.GetContextObject<BuildParametersContext>(); var buildParameters = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>(); var buildMapContext = context.GetContextObject<BuildMapContext>();
List<string> buildedBundles = buildResults.BundleInfos.Keys.ToList(); List<string> unityCreateBundles = buildResults.BundleInfos.Keys.ToList();
// 1. 过滤掉原生Bundle // 1. 过滤掉原生Bundle
List<string> expectBundles = buildMapContext.BundleInfos.Where(t => t.IsRawFile == false).Select(t => t.BundleName).ToList(); List<string> expectBundles = buildMapContext.Collection.Where(t => t.IsRawFile == false).Select(t => t.BundleName).ToList();
// 2. 验证Bundle // 2. 验证Bundle
List<string> exceptBundleList1 = buildedBundles.Except(expectBundles).ToList(); List<string> exceptBundleList1 = unityCreateBundles.Except(expectBundles).ToList();
if (exceptBundleList1.Count > 0) if (exceptBundleList1.Count > 0)
{ {
foreach (var exceptBundle in exceptBundleList1) foreach (var exceptBundle in exceptBundleList1)
{ {
Debug.LogWarning($"差异资源包: {exceptBundle}"); BuildLogger.Warning($"差异资源包: {exceptBundle}");
} }
throw new System.Exception("存在差异资源包!请查看警告信息!"); throw new System.Exception("存在差异资源包!请查看警告信息!");
} }
// 3. 验证Bundle // 3. 验证Bundle
List<string> exceptBundleList2 = expectBundles.Except(buildedBundles).ToList(); List<string> exceptBundleList2 = expectBundles.Except(unityCreateBundles).ToList();
if (exceptBundleList2.Count > 0) if (exceptBundleList2.Count > 0)
{ {
foreach (var exceptBundle in exceptBundleList2) foreach (var exceptBundle in exceptBundleList2)
{ {
Debug.LogWarning($"差异资源包: {exceptBundle}"); BuildLogger.Warning($"差异资源包: {exceptBundle}");
} }
throw new System.Exception("存在差异资源包!请查看警告信息!"); throw new System.Exception("存在差异资源包!请查看警告信息!");
} }
BuildRunner.Log("构建结果验证成功!"); BuildLogger.Log("构建结果验证成功!");
} }
} }
} }

View File

@@ -0,0 +1,11 @@

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

View File

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

View File

@@ -217,7 +217,7 @@ namespace YooAsset.Editor
private CollectAssetInfo CreateCollectAssetInfo(CollectCommand command, AssetBundleCollectorGroup group, string assetPath, bool isRawFilePackRule) private CollectAssetInfo CreateCollectAssetInfo(CollectCommand command, AssetBundleCollectorGroup group, string assetPath, bool isRawFilePackRule)
{ {
string address = GetAddress(group, assetPath); string address = GetAddress(command, group, assetPath);
string bundleName = GetBundleName(command, group, assetPath); string bundleName = GetBundleName(command, group, assetPath);
List<string> assetTags = GetAssetTags(group); List<string> assetTags = GetAssetTags(group);
CollectAssetInfo collectAssetInfo = new CollectAssetInfo(CollectorType, bundleName, address, assetPath, isRawFilePackRule, assetTags); CollectAssetInfo collectAssetInfo = new CollectAssetInfo(CollectorType, bundleName, address, assetPath, isRawFilePackRule, assetTags);
@@ -280,20 +280,11 @@ namespace YooAsset.Editor
} }
string fileExtension = System.IO.Path.GetExtension(assetPath); string fileExtension = System.IO.Path.GetExtension(assetPath);
if (IsIgnoreFile(fileExtension)) if (DefaultFilterRule.IsIgnoreFile(fileExtension))
return false; return false;
return true; return true;
} }
private bool IsIgnoreFile(string fileExtension)
{
foreach (var extension in DefaultFilterRule.IgnoreFileExtensions)
{
if (extension == fileExtension)
return true;
}
return false;
}
private bool IsCollectAsset(string assetPath) private bool IsCollectAsset(string assetPath)
{ {
Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath); Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
@@ -304,8 +295,11 @@ namespace YooAsset.Editor
IFilterRule filterRuleInstance = AssetBundleCollectorSettingData.GetFilterRuleInstance(FilterRuleName); IFilterRule filterRuleInstance = AssetBundleCollectorSettingData.GetFilterRuleInstance(FilterRuleName);
return filterRuleInstance.IsCollectAsset(new FilterRuleData(assetPath)); return filterRuleInstance.IsCollectAsset(new FilterRuleData(assetPath));
} }
private string GetAddress(AssetBundleCollectorGroup group, string assetPath) private string GetAddress(CollectCommand command, AssetBundleCollectorGroup group, string assetPath)
{ {
if (command.EnableAddressable == false)
return string.Empty;
if (CollectorType != ECollectorType.MainAssetCollector) if (CollectorType != ECollectorType.MainAssetCollector)
return string.Empty; return string.Empty;

View File

@@ -100,7 +100,7 @@ namespace YooAsset.Editor
{ {
if (package.PackageName == packageName) if (package.PackageName == packageName)
{ {
CollectCommand command = new CollectCommand(buildMode, package.PackageName, EnableAddressable, UniqueBundleName); CollectCommand command = new CollectCommand(buildMode, packageName, EnableAddressable, UniqueBundleName);
CollectResult collectResult = new CollectResult(command); CollectResult collectResult = new CollectResult(command);
collectResult.SetCollectAssets(package.GetAllCollectAssets(command)); collectResult.SetCollectAssets(package.GetAllCollectAssets(command));
return collectResult; return collectResult;
@@ -109,21 +109,5 @@ namespace YooAsset.Editor
throw new Exception($"Not found collector pacakge : {packageName}"); throw new Exception($"Not found collector pacakge : {packageName}");
} }
/// <summary>
/// 获取所有包裹收集的资源文件
/// </summary>
public List<CollectResult> GetAllPackageAssets(EBuildMode buildMode)
{
List<CollectResult> collectResultList = new List<CollectResult>(1000);
foreach (var package in Packages)
{
CollectCommand command = new CollectCommand(buildMode, package.PackageName, EnableAddressable, UniqueBundleName);
CollectResult collectResult = new CollectResult(command);
collectResult.SetCollectAssets(package.GetAllCollectAssets(command));
collectResultList.Add(collectResult);
}
return collectResultList;
}
} }
} }

View File

@@ -794,7 +794,7 @@ namespace YooAsset.Editor
try try
{ {
CollectCommand command = new CollectCommand(EBuildMode.DryRunBuild, _packageNameTxt.value, _enableAddressableToogle.value, _uniqueBundleNameToogle.value); CollectCommand command = new CollectCommand(EBuildMode.SimulateBuild, _packageNameTxt.value, _enableAddressableToogle.value, _uniqueBundleNameToogle.value);
collectAssetInfos = collector.GetAllCollectAssets(command, group); collectAssetInfos = collector.GetAllCollectAssets(command, group);
} }
catch (System.Exception e) catch (System.Exception e)
@@ -812,12 +812,7 @@ namespace YooAsset.Editor
string showInfo = collectAssetInfo.AssetPath; string showInfo = collectAssetInfo.AssetPath;
if (_enableAddressableToogle.value) if (_enableAddressableToogle.value)
{ showInfo = $"[{collectAssetInfo.Address}] {collectAssetInfo.AssetPath}";
IAddressRule instance = AssetBundleCollectorSettingData.GetAddressRuleInstance(collector.AddressRuleName);
AddressRuleData ruleData = new AddressRuleData(collectAssetInfo.AssetPath, collector.CollectPath, group.GroupName, collector.UserData);
string addressValue = instance.GetAssetAddress(ruleData);
showInfo = $"[{addressValue}] {showInfo}";
}
var label = new Label(); var label = new Label();
label.text = showInfo; label.text = showInfo;

View File

@@ -23,12 +23,22 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public bool UniqueBundleName { private set; get; } public bool UniqueBundleName { private set; get; }
/// <summary>
/// 着色器统一全名称
/// </summary>
public string ShadersBundleName { private set; get; }
public CollectCommand(EBuildMode buildMode, string packageName, bool enableAddressable, bool uniqueBundleName) public CollectCommand(EBuildMode buildMode, string packageName, bool enableAddressable, bool uniqueBundleName)
{ {
BuildMode = buildMode; BuildMode = buildMode;
PackageName = packageName; PackageName = packageName;
EnableAddressable = enableAddressable; EnableAddressable = enableAddressable;
UniqueBundleName = uniqueBundleName; UniqueBundleName = uniqueBundleName;
// 着色器统一全名称
var packRuleResult = DefaultPackRule.CreateShadersPackRuleResult();
ShadersBundleName = packRuleResult.GetMainBundleName(packageName, uniqueBundleName);
} }
} }
} }

View File

@@ -10,26 +10,15 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public CollectCommand Command { private set; get; } public CollectCommand Command { private set; get; }
/// <summary>
/// 着色器统一全名称
/// </summary>
public string ShadersBundleName { private set; get; }
/// <summary> /// <summary>
/// 收集的资源信息列表 /// 收集的资源信息列表
/// </summary> /// </summary>
public List<CollectAssetInfo> CollectAssets { private set; get; } public List<CollectAssetInfo> CollectAssets { private set; get; }
public CollectResult(CollectCommand command) public CollectResult(CollectCommand command)
{ {
Command = command; Command = command;
// 着色器统一全名称
var packRuleResult = DefaultPackRule.CreateShadersPackRuleResult();
ShadersBundleName = packRuleResult.GetMainBundleName(command.PackageName, command.UniqueBundleName);
} }
public void SetCollectAssets(List<CollectAssetInfo> collectAssets) public void SetCollectAssets(List<CollectAssetInfo> collectAssets)
{ {
CollectAssets = collectAssets; CollectAssets = collectAssets;

View File

@@ -27,8 +27,8 @@ namespace YooAsset.Editor
string IAddressRule.GetAssetAddress(AddressRuleData data) string IAddressRule.GetAssetAddress(AddressRuleData data)
{ {
string fileName = Path.GetFileNameWithoutExtension(data.AssetPath); string fileName = Path.GetFileNameWithoutExtension(data.AssetPath);
string collectorName = Path.GetFileNameWithoutExtension(data.CollectPath); FileInfo fileInfo = new FileInfo(data.AssetPath);
return $"{collectorName}_{fileName}"; return $"{fileInfo.Directory.Name}_{fileName}";
} }
} }
} }

View File

@@ -1,6 +1,8 @@
using UnityEngine; using System.Collections;
using UnityEditor; using System.Collections.Generic;
using System.IO; using System.IO;
using UnityEngine;
using UnityEditor;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
@@ -9,7 +11,15 @@ namespace YooAsset.Editor
/// <summary> /// <summary>
/// 忽略的文件类型 /// 忽略的文件类型
/// </summary> /// </summary>
public static readonly string[] IgnoreFileExtensions = { "", ".so", ".dll", ".cs", ".js", ".boo", ".meta", ".cginc", ".hlsl" }; private readonly static HashSet<string> _ignoreFileExtensions = new HashSet<string>() { "", ".so", ".dll", ".cs", ".js", ".boo", ".meta", ".cginc", ".hlsl" };
/// <summary>
/// 查询是否为忽略文件
/// </summary>
public static bool IsIgnoreFile(string fileExtension)
{
return _ignoreFileExtensions.Contains(fileExtension);
}
} }
[DisplayName("收集所有资源")] [DisplayName("收集所有资源")]

View File

@@ -10,50 +10,6 @@ namespace YooAsset.Editor
#if UNITY_2019_4_OR_NEWER #if UNITY_2019_4_OR_NEWER
private readonly static Dictionary<System.Type, string> _uxmlDic = new Dictionary<System.Type, string>(); private readonly static Dictionary<System.Type, string> _uxmlDic = new Dictionary<System.Type, string>();
/*
static EditorHelper()
{
// 资源包收集
_uxmlDic.Add(typeof(AssetBundleCollectorWindow), "355c4ac5cdebddc4c8362bed6f17a79e");
// 资源包构建
_uxmlDic.Add(typeof(AssetBundleBuilderWindow), "28ba29adb4949284e8c48893218b0d9a");
// 资源包调试
_uxmlDic.Add(typeof(AssetBundleDebuggerWindow), "790db12999afd334e8fb6ba70ef0a947");
_uxmlDic.Add(typeof(DebuggerAssetListViewer), "31c6096c1cb29b4469096b7b4942a322");
_uxmlDic.Add(typeof(DebuggerBundleListViewer), "932a25ffd05c13c47994d66e9d73bc37");
// 构建报告
_uxmlDic.Add(typeof(AssetBundleReporterWindow), "9052b72c383e95043a0c7e7f369b1ad7");
_uxmlDic.Add(typeof(ReporterSummaryViewer), "f8929271050855e42a1ccc6b14993a04");
_uxmlDic.Add(typeof(ReporterAssetListViewer), "5f81bc15a55ee0a49a266f9d71e2372b");
_uxmlDic.Add(typeof(ReporterBundleListViewer), "56d6dbe0d65ce334a8996beb19612989");
}
/// <summary>
/// 加载窗口的布局文件
/// </summary>
public static UnityEngine.UIElements.VisualTreeAsset LoadWindowUXML<TWindow>() where TWindow : class
{
var windowType = typeof(TWindow);
if (_uxmlDic.TryGetValue(windowType, out string uxmlGUID))
{
string assetPath = AssetDatabase.GUIDToAssetPath(uxmlGUID);
if (string.IsNullOrEmpty(assetPath))
throw new System.Exception($"Invalid YooAsset uxml guid : {uxmlGUID}");
var visualTreeAsset = AssetDatabase.LoadAssetAtPath<UnityEngine.UIElements.VisualTreeAsset>(assetPath);
if (visualTreeAsset == null)
throw new System.Exception($"Failed to load {windowType}.uxml");
return visualTreeAsset;
}
else
{
throw new System.Exception($"Invalid YooAsset window type : {windowType}");
}
}
*/
/// <summary> /// <summary>
/// 加载窗口的布局文件 /// 加载窗口的布局文件
/// </summary> /// </summary>

View File

@@ -13,5 +13,10 @@ namespace YooAsset.Editor
/// 收集的包裹名称 /// 收集的包裹名称
/// </summary> /// </summary>
public string CollectPackage = string.Empty; public string CollectPackage = string.Empty;
/// <summary>
/// 容器值
/// </summary>
public int ProcessCapacity = 1000;
} }
} }

View File

@@ -24,6 +24,7 @@ namespace YooAsset.Editor
private TextField _collectOutputField; private TextField _collectOutputField;
private Label _currentShaderCountField; private Label _currentShaderCountField;
private Label _currentVariantCountField; private Label _currentVariantCountField;
private SliderInt _processCapacitySlider;
private PopupField<string> _packageField; private PopupField<string> _packageField;
public void CreateGUI() public void CreateGUI()
@@ -72,6 +73,23 @@ namespace YooAsset.Editor
packageContainer.Add(_packageField); packageContainer.Add(_packageField);
} }
// 容器值
_processCapacitySlider = root.Q<SliderInt>("ProcessCapacity");
_processCapacitySlider.SetValueWithoutNotify(ShaderVariantCollectorSettingData.Setting.ProcessCapacity);
#if !UNITY_2020_3_OR_NEWER
_processCapacitySlider.label = $"Capacity ({_processCapacitySlider.value})";
_processCapacitySlider.RegisterValueChangedCallback(evt =>
{
ShaderVariantCollectorSettingData.Setting.ProcessCapacity = _processCapacitySlider.value;
_processCapacitySlider.label = $"Capacity ({_processCapacitySlider.value})";
});
#else
_processCapacitySlider.RegisterValueChangedCallback(evt =>
{
ShaderVariantCollectorSettingData.Setting.ProcessCapacity = _processCapacitySlider.value;
});
#endif
_currentShaderCountField = root.Q<Label>("CurrentShaderCount"); _currentShaderCountField = root.Q<Label>("CurrentShaderCount");
_currentVariantCountField = root.Q<Label>("CurrentVariantCount"); _currentVariantCountField = root.Q<Label>("CurrentVariantCount");
@@ -103,7 +121,8 @@ namespace YooAsset.Editor
{ {
string savePath = ShaderVariantCollectorSettingData.Setting.SavePath; string savePath = ShaderVariantCollectorSettingData.Setting.SavePath;
string packageName = ShaderVariantCollectorSettingData.Setting.CollectPackage; string packageName = ShaderVariantCollectorSettingData.Setting.CollectPackage;
ShaderVariantCollector.Run(savePath, packageName, int.MaxValue, null); int processCapacity = _processCapacitySlider.value;
ShaderVariantCollector.Run(savePath, packageName, processCapacity, null);
} }
// 构建包裹相关 // 构建包裹相关

View File

@@ -1,10 +1,11 @@
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements"> <ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements">
<uie:Toolbar name="Toolbar" style="display: flex; flex-direction: row-reverse;" />
<ui:VisualElement name="CollectContainer"> <ui:VisualElement name="CollectContainer">
<uie:Toolbar name="Toolbar" style="display: flex; flex-direction: row-reverse;" />
<ui:TextField picking-mode="Ignore" label="文件保存路径" name="CollectOutput" style="height: 22px;" /> <ui:TextField picking-mode="Ignore" label="文件保存路径" name="CollectOutput" style="height: 22px;" />
<ui:VisualElement name="PackageContainer" style="height: 24px;" /> <ui:VisualElement name="PackageContainer" style="height: 24px;" />
<ui:Label text="Current Shader Count" display-tooltip-when-elided="true" name="CurrentShaderCount" style="height: 20px; padding-left: 4px;" /> <ui:Label text="Current Shader Count" display-tooltip-when-elided="true" name="CurrentShaderCount" style="height: 20px; padding-left: 4px;" />
<ui:Label text="Current Variant Count" display-tooltip-when-elided="true" name="CurrentVariantCount" style="height: 20px; padding-left: 4px;" /> <ui:Label text="Current Variant Count" display-tooltip-when-elided="true" name="CurrentVariantCount" style="height: 20px; padding-left: 4px;" />
<ui:SliderInt picking-mode="Ignore" label="Capacity" value="9999" high-value="1000" name="ProcessCapacity" low-value="10" show-input-field="true" />
<ui:Button text="开始搜集" display-tooltip-when-elided="true" name="CollectButton" style="height: 50px; background-color: rgb(40, 106, 42); margin-top: 10px;" /> <ui:Button text="开始搜集" display-tooltip-when-elided="true" name="CollectButton" style="height: 50px; background-color: rgb(40, 106, 42); margin-top: 10px;" />
</ui:VisualElement> </ui:VisualElement>
</ui:UXML> </ui:UXML>

View File

@@ -8,11 +8,16 @@ namespace YooAsset
{ {
internal class AssetSystemImpl internal class AssetSystemImpl
{ {
private readonly List<BundleLoaderBase> _loaders = new List<BundleLoaderBase>(1000); private readonly Dictionary<string, BundleLoaderBase> _loaderDic = new Dictionary<string, BundleLoaderBase>(5000);
private readonly List<ProviderBase> _providers = new List<ProviderBase>(1000); private readonly List<BundleLoaderBase> _loaderList = new List<BundleLoaderBase>(5000);
private readonly Dictionary<string, ProviderBase> _providerDic = new Dictionary<string, ProviderBase>(5000);
private readonly List<ProviderBase> _providerList = new List<ProviderBase>(5000);
private readonly static Dictionary<string, SceneOperationHandle> _sceneHandles = new Dictionary<string, SceneOperationHandle>(100); private readonly static Dictionary<string, SceneOperationHandle> _sceneHandles = new Dictionary<string, SceneOperationHandle>(100);
private static long _sceneCreateCount = 0; private static long _sceneCreateCount = 0;
private bool _isUnloadSafe = true;
private string _packageName; private string _packageName;
private bool _simulationOnEditor; private bool _simulationOnEditor;
private int _loadingMaxNumber; private int _loadingMaxNumber;
@@ -39,7 +44,7 @@ namespace YooAsset
public void Update() public void Update()
{ {
// 更新加载器 // 更新加载器
foreach (var loader in _loaders) foreach (var loader in _loaderList)
{ {
loader.Update(); loader.Update();
} }
@@ -47,10 +52,11 @@ namespace YooAsset
// 更新资源提供者 // 更新资源提供者
// 注意:循环更新的时候,可能会扩展列表 // 注意:循环更新的时候,可能会扩展列表
// 注意:不能限制场景对象的加载 // 注意:不能限制场景对象的加载
_isUnloadSafe = false;
int loadingCount = 0; int loadingCount = 0;
for (int i = 0; i < _providers.Count; i++) for (int i = 0; i < _providerList.Count; i++)
{ {
var provider = _providers[i]; var provider = _providerList[i];
if (provider.IsSceneProvider()) if (provider.IsSceneProvider())
{ {
provider.Update(); provider.Update();
@@ -64,6 +70,7 @@ namespace YooAsset
loadingCount++; loadingCount++;
} }
} }
_isUnloadSafe = true;
} }
/// <summary> /// <summary>
@@ -71,17 +78,19 @@ namespace YooAsset
/// </summary> /// </summary>
public void DestroyAll() public void DestroyAll()
{ {
foreach (var provider in _providers) foreach (var provider in _providerList)
{ {
provider.Destroy(); provider.Destroy();
} }
_providers.Clear(); _providerList.Clear();
_providerDic.Clear();
foreach (var loader in _loaders) foreach (var loader in _loaderList)
{ {
loader.Destroy(true); loader.Destroy(true);
} }
_loaders.Clear(); _loaderList.Clear();
_loaderDic.Clear();
ClearSceneHandle(); ClearSceneHandle();
DecryptionServices = null; DecryptionServices = null;
@@ -93,6 +102,12 @@ namespace YooAsset
/// </summary> /// </summary>
public void UnloadUnusedAssets() public void UnloadUnusedAssets()
{ {
if (_isUnloadSafe == false)
{
YooLogger.Warning("Can not unload unused assets when processing resource loading !");
return;
}
// 注意:资源包之间可能存在多层深层嵌套,需要多次循环释放。 // 注意:资源包之间可能存在多层深层嵌套,需要多次循环释放。
int loopCount = 10; int loopCount = 10;
for (int i = 0; i < loopCount; i++) for (int i = 0; i < loopCount; i++)
@@ -104,29 +119,33 @@ namespace YooAsset
{ {
if (_simulationOnEditor) if (_simulationOnEditor)
{ {
for (int i = _providers.Count - 1; i >= 0; i--) for (int i = _providerList.Count - 1; i >= 0; i--)
{ {
if (_providers[i].CanDestroy()) var provider = _providerList[i];
if (provider.CanDestroy())
{ {
_providers[i].Destroy(); provider.Destroy();
_providers.RemoveAt(i); _providerList.RemoveAt(i);
_providerDic.Remove(provider.ProviderGUID);
} }
} }
} }
else else
{ {
for (int i = _loaders.Count - 1; i >= 0; i--) for (int i = _loaderList.Count - 1; i >= 0; i--)
{ {
BundleLoaderBase loader = _loaders[i]; BundleLoaderBase loader = _loaderList[i];
loader.TryDestroyAllProviders(); loader.TryDestroyAllProviders();
} }
for (int i = _loaders.Count - 1; i >= 0; i--) for (int i = _loaderList.Count - 1; i >= 0; i--)
{ {
BundleLoaderBase loader = _loaders[i]; BundleLoaderBase loader = _loaderList[i];
if (loader.CanDestroy()) if (loader.CanDestroy())
{ {
string bundleName = loader.MainBundleInfo.Bundle.BundleName;
loader.Destroy(false); loader.Destroy(false);
_loaders.RemoveAt(i); _loaderList.RemoveAt(i);
_loaderDic.Remove(bundleName);
} }
} }
} }
@@ -137,17 +156,19 @@ namespace YooAsset
/// </summary> /// </summary>
public void ForceUnloadAllAssets() public void ForceUnloadAllAssets()
{ {
foreach (var provider in _providers) foreach (var provider in _providerList)
{ {
provider.Destroy(); provider.Destroy();
} }
foreach (var loader in _loaders) foreach (var loader in _loaderList)
{ {
loader.Destroy(true); loader.Destroy(true);
} }
_providers.Clear(); _providerList.Clear();
_loaders.Clear(); _providerDic.Clear();
_loaderList.Clear();
_loaderDic.Clear();
ClearSceneHandle(); ClearSceneHandle();
// 注意:调用底层接口释放所有资源 // 注意:调用底层接口释放所有资源
@@ -182,7 +203,8 @@ namespace YooAsset
else else
provider = new BundledSceneProvider(this, providerGUID, assetInfo, sceneMode, activateOnLoad, priority); provider = new BundledSceneProvider(this, providerGUID, assetInfo, sceneMode, activateOnLoad, priority);
provider.InitSpawnDebugInfo(); provider.InitSpawnDebugInfo();
_providers.Add(provider); _providerList.Add(provider);
_providerDic.Add(providerGUID, provider);
} }
var handle = provider.CreateHandle<SceneOperationHandle>(); var handle = provider.CreateHandle<SceneOperationHandle>();
@@ -213,7 +235,8 @@ namespace YooAsset
else else
provider = new BundledAssetProvider(this, providerGUID, assetInfo); provider = new BundledAssetProvider(this, providerGUID, assetInfo);
provider.InitSpawnDebugInfo(); provider.InitSpawnDebugInfo();
_providers.Add(provider); _providerList.Add(provider);
_providerDic.Add(providerGUID, provider);
} }
return provider.CreateHandle<AssetOperationHandle>(); return provider.CreateHandle<AssetOperationHandle>();
} }
@@ -240,7 +263,8 @@ namespace YooAsset
else else
provider = new BundledSubAssetsProvider(this, providerGUID, assetInfo); provider = new BundledSubAssetsProvider(this, providerGUID, assetInfo);
provider.InitSpawnDebugInfo(); provider.InitSpawnDebugInfo();
_providers.Add(provider); _providerList.Add(provider);
_providerDic.Add(providerGUID, provider);
} }
return provider.CreateHandle<SubAssetsOperationHandle>(); return provider.CreateHandle<SubAssetsOperationHandle>();
} }
@@ -267,7 +291,8 @@ namespace YooAsset
else else
provider = new BundledRawFileProvider(this, providerGUID, assetInfo); provider = new BundledRawFileProvider(this, providerGUID, assetInfo);
provider.InitSpawnDebugInfo(); provider.InitSpawnDebugInfo();
_providers.Add(provider); _providerList.Add(provider);
_providerDic.Add(providerGUID, provider);
} }
return provider.CreateHandle<RawFileOperationHandle>(); return provider.CreateHandle<RawFileOperationHandle>();
} }
@@ -338,29 +363,31 @@ namespace YooAsset
{ {
foreach (var provider in providers) foreach (var provider in providers)
{ {
_providers.Remove(provider); _providerList.Remove(provider);
_providerDic.Remove(provider.ProviderGUID);
} }
} }
internal bool CheckBundleCanDestroy(int bundleID) internal bool CheckBundleDestroyed(int bundleID)
{ {
string bundleName = BundleServices.GetBundleName(bundleID); string bundleName = BundleServices.GetBundleName(bundleID);
BundleLoaderBase loader = TryGetAssetBundleLoader(bundleName); BundleLoaderBase loader = TryGetAssetBundleLoader(bundleName);
if (loader == null) if (loader == null)
return true; return true;
return loader.CanDestroy(); return loader.IsDestroyed;
} }
private BundleLoaderBase CreateAssetBundleLoaderInternal(BundleInfo bundleInfo) private BundleLoaderBase CreateAssetBundleLoaderInternal(BundleInfo bundleInfo)
{ {
// 如果加载器已经存在 // 如果加载器已经存在
BundleLoaderBase loader = TryGetAssetBundleLoader(bundleInfo.Bundle.BundleName); string bundleName = bundleInfo.Bundle.BundleName;
BundleLoaderBase loader = TryGetAssetBundleLoader(bundleName);
if (loader != null) if (loader != null)
return loader; return loader;
// 新增下载需求 // 新增下载需求
#if UNITY_WEBGL #if UNITY_WEBGL
if (bundleInfo.Bundle.IsRawFile) if (bundleInfo.Bundle.IsRawFile)
loader = new RawBundleFileLoader(this, bundleInfo); loader = new RawBundleWebLoader(this, bundleInfo);
else else
loader = new AssetBundleWebLoader(this, bundleInfo); loader = new AssetBundleWebLoader(this, bundleInfo);
#else #else
@@ -370,43 +397,30 @@ namespace YooAsset
loader = new AssetBundleFileLoader(this, bundleInfo); loader = new AssetBundleFileLoader(this, bundleInfo);
#endif #endif
_loaders.Add(loader); _loaderList.Add(loader);
_loaderDic.Add(bundleName, loader);
return loader; return loader;
} }
private BundleLoaderBase TryGetAssetBundleLoader(string bundleName) private BundleLoaderBase TryGetAssetBundleLoader(string bundleName)
{ {
BundleLoaderBase loader = null; if (_loaderDic.TryGetValue(bundleName, out BundleLoaderBase value))
for (int i = 0; i < _loaders.Count; i++) return value;
{ else
BundleLoaderBase temp = _loaders[i]; return null;
if (temp.MainBundleInfo.Bundle.BundleName.Equals(bundleName))
{
loader = temp;
break;
}
}
return loader;
} }
private ProviderBase TryGetProvider(string providerGUID) private ProviderBase TryGetProvider(string providerGUID)
{ {
ProviderBase provider = null; if (_providerDic.TryGetValue(providerGUID, out ProviderBase value))
for (int i = 0; i < _providers.Count; i++) return value;
{ else
ProviderBase temp = _providers[i]; return null;
if (temp.ProviderGUID.Equals(providerGUID))
{
provider = temp;
break;
}
}
return provider;
} }
#region #region
internal List<DebugProviderInfo> GetDebugReportInfos() internal List<DebugProviderInfo> GetDebugReportInfos()
{ {
List<DebugProviderInfo> result = new List<DebugProviderInfo>(_providers.Count); List<DebugProviderInfo> result = new List<DebugProviderInfo>(_providerList.Count);
foreach (var provider in _providers) foreach (var provider in _providerList)
{ {
DebugProviderInfo providerInfo = new DebugProviderInfo(); DebugProviderInfo providerInfo = new DebugProviderInfo();
providerInfo.AssetPath = provider.MainAssetInfo.AssetPath; providerInfo.AssetPath = provider.MainAssetInfo.AssetPath;
@@ -429,9 +443,9 @@ namespace YooAsset
internal List<BundleInfo> GetLoadedBundleInfos() internal List<BundleInfo> GetLoadedBundleInfos()
{ {
List<BundleInfo> result = new List<BundleInfo>(100); List<BundleInfo> result = new List<BundleInfo>(100);
foreach (var bundleLoader in _loaders) foreach (var loader in _loaderList)
{ {
result.Add(bundleLoader.MainBundleInfo); result.Add(loader.MainBundleInfo);
} }
return result; return result;
} }

View File

@@ -26,7 +26,7 @@ namespace YooAsset
private DownloaderBase _unpacker; private DownloaderBase _unpacker;
private DownloaderBase _downloader; private DownloaderBase _downloader;
private AssetBundleCreateRequest _createRequest; private AssetBundleCreateRequest _createRequest;
private FileStream _fileStream; private Stream _stream;
public AssetBundleFileLoader(AssetSystemImpl impl, BundleInfo bundleInfo) : base(impl, bundleInfo) public AssetBundleFileLoader(AssetSystemImpl impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
@@ -196,12 +196,12 @@ namespace YooAsset
} }
else if (loadMethod == EBundleLoadMethod.LoadFromStream) else if (loadMethod == EBundleLoadMethod.LoadFromStream)
{ {
_fileStream = Impl.DecryptionServices.LoadFromStream(fileInfo); _stream = Impl.DecryptionServices.LoadFromStream(fileInfo);
uint managedReadBufferSize = Impl.DecryptionServices.GetManagedReadBufferSize(); uint managedReadBufferSize = Impl.DecryptionServices.GetManagedReadBufferSize();
if (_isWaitForAsyncComplete) if (_isWaitForAsyncComplete)
CacheBundle = AssetBundle.LoadFromStream(_fileStream, 0, managedReadBufferSize); CacheBundle = AssetBundle.LoadFromStream(_stream, 0, managedReadBufferSize);
else else
_createRequest = AssetBundle.LoadFromStreamAsync(_fileStream, 0, managedReadBufferSize); _createRequest = AssetBundle.LoadFromStreamAsync(_stream, 0, managedReadBufferSize);
} }
else else
{ {
@@ -265,11 +265,11 @@ namespace YooAsset
{ {
base.Destroy(forceDestroy); base.Destroy(forceDestroy);
if (_fileStream != null) if (_stream != null)
{ {
_fileStream.Close(); _stream.Close();
_fileStream.Dispose(); _stream.Dispose();
_fileStream = null; _stream = null;
} }
} }
@@ -286,9 +286,12 @@ namespace YooAsset
// 文件解压 // 文件解压
if (_unpacker != null) if (_unpacker != null)
{ {
_unpacker.Update();
if (_unpacker.IsDone() == false) if (_unpacker.IsDone() == false)
{
_unpacker.WaitForAsyncComplete = true;
_unpacker.Update();
continue; continue;
}
} }
// 保险机制 // 保险机制
@@ -299,7 +302,7 @@ namespace YooAsset
if (_isShowWaitForAsyncError == false) if (_isShowWaitForAsyncError == false)
{ {
_isShowWaitForAsyncError = true; _isShowWaitForAsyncError = true;
YooLogger.Error($"WaitForAsyncComplete failed ! Try load bundle : {MainBundleInfo.Bundle.BundleName} from remote with sync load method !"); YooLogger.Error($"{nameof(WaitForAsyncComplete)} failed ! Try load bundle : {MainBundleInfo.Bundle.BundleName} from remote with sync load method !");
} }
break; break;
} }

View File

@@ -7,6 +7,9 @@ using UnityEngine.Networking;
namespace YooAsset namespace YooAsset
{ {
/// <summary>
/// WebGL平台加载器
/// </summary>
internal sealed class AssetBundleWebLoader : BundleLoaderBase internal sealed class AssetBundleWebLoader : BundleLoaderBase
{ {
private enum ESteps private enum ESteps
@@ -24,7 +27,6 @@ namespace YooAsset
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
private float _tryTimer = 0; private float _tryTimer = 0;
private bool _isShowWaitForAsyncError = false;
private DownloaderBase _downloader; private DownloaderBase _downloader;
private UnityWebRequest _webRequest; private UnityWebRequest _webRequest;
private AssetBundleCreateRequest _createRequest; private AssetBundleCreateRequest _createRequest;
@@ -225,10 +227,11 @@ namespace YooAsset
/// </summary> /// </summary>
public override void WaitForAsyncComplete() public override void WaitForAsyncComplete()
{ {
if (_isShowWaitForAsyncError == false) if (IsDone() == false)
{ {
_isShowWaitForAsyncError = true; Status = EStatus.Failed;
YooLogger.Error($"WebGL platform not support {nameof(WaitForAsyncComplete)} ! Use the async load method instead of the sync load method !"); LastError = $"{nameof(WaitForAsyncComplete)} failed ! WebGL platform not support sync load method !";
YooLogger.Error(LastError);
} }
} }
} }

View File

@@ -100,7 +100,18 @@ namespace YooAsset
if (IsDone() == false) if (IsDone() == false)
return false; return false;
return RefCount <= 0; if (RefCount > 0)
return false;
// 检查引用链上的资源包是否已经全部销毁
// 注意:互相引用的资源包无法卸载!
foreach (var bundleID in MainBundleInfo.Bundle.ReferenceIDs)
{
if (Impl.CheckBundleDestroyed(bundleID) == false)
return false;
}
return true;
} }
/// <summary> /// <summary>
@@ -122,24 +133,15 @@ namespace YooAsset
if (RefCount > _providers.Count) if (RefCount > _providers.Count)
return; return;
// 条件3检查依赖链上的资源包
// 依赖该资源包的所有资源包可以销毁
// 注意:互相引用的资源包无法卸载!
foreach (var bundleID in MainBundleInfo.Bundle.ReferenceIDs)
{
if (Impl.CheckBundleCanDestroy(bundleID) == false)
return;
}
// 销毁所有Providers // 销毁所有Providers
foreach (var provider in _providers)
{ {
provider.Destroy(); foreach (var provider in _providers)
{
provider.Destroy();
}
Impl.RemoveBundleProviders(_providers);
_providers.Clear();
} }
// 从列表里移除Providers
Impl.RemoveBundleProviders(_providers);
_providers.Clear();
} }

View File

@@ -16,7 +16,6 @@ namespace YooAsset
} }
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
private bool _isShowWaitForAsyncError = false;
private DownloaderBase _unpacker; private DownloaderBase _unpacker;
private DownloaderBase _downloader; private DownloaderBase _downloader;
@@ -42,7 +41,7 @@ namespace YooAsset
} }
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming) else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{ {
#if UNITY_ANDROID || UNITY_WEBGL #if UNITY_ANDROID
_steps = ESteps.Unpack; _steps = ESteps.Unpack;
FileLoadPath = MainBundleInfo.Bundle.CachedDataFilePath; FileLoadPath = MainBundleInfo.Bundle.CachedDataFilePath;
#else #else
@@ -125,13 +124,14 @@ namespace YooAsset
DownloadProgress = 1f; DownloadProgress = 1f;
DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize; DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize;
_steps = ESteps.Done;
if (File.Exists(FileLoadPath)) if (File.Exists(FileLoadPath))
{ {
_steps = ESteps.Done;
Status = EStatus.Succeed; Status = EStatus.Succeed;
} }
else else
{ {
_steps = ESteps.Done;
Status = EStatus.Failed; Status = EStatus.Failed;
LastError = $"Raw file not found : {FileLoadPath}"; LastError = $"Raw file not found : {FileLoadPath}";
} }
@@ -149,20 +149,24 @@ namespace YooAsset
// 文件解压 // 文件解压
if (_unpacker != null) if (_unpacker != null)
{ {
_unpacker.Update();
if (_unpacker.IsDone() == false) if (_unpacker.IsDone() == false)
{
_unpacker.WaitForAsyncComplete = true;
_unpacker.Update();
continue; continue;
}
} }
// 保险机制 // 保险机制
// 注意:如果需要从WEB端下载资源,可能会触发保险机制! // 注意:如果需要从端下载资源,可能会触发保险机制!
frame--; frame--;
if (frame == 0) if (frame == 0)
{ {
if (_isShowWaitForAsyncError == false) if (IsDone() == false)
{ {
_isShowWaitForAsyncError = true; Status = EStatus.Failed;
YooLogger.Error($"WaitForAsyncComplete failed ! Try load bundle : {MainBundleInfo.Bundle.BundleName} from remote with sync load method !"); LastError = $"WaitForAsyncComplete failed ! Try load bundle : {MainBundleInfo.Bundle.BundleName} from remote with sync load method !";
YooLogger.Error(LastError);
} }
break; break;
} }

View File

@@ -0,0 +1,151 @@
using System.IO;
namespace YooAsset
{
/// <summary>
/// WebGL平台加载器
/// </summary>
internal class RawBundleWebLoader : BundleLoaderBase
{
private enum ESteps
{
None,
Download,
CheckDownload,
Website,
CheckWebsite,
CheckFile,
Done,
}
private ESteps _steps = ESteps.None;
private DownloaderBase _website;
private DownloaderBase _downloader;
public RawBundleWebLoader(AssetSystemImpl impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
{
}
/// <summary>
/// 轮询更新
/// </summary>
public override void Update()
{
if (_steps == ESteps.Done)
return;
if (_steps == ESteps.None)
{
if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
{
_steps = ESteps.Download;
FileLoadPath = MainBundleInfo.Bundle.CachedDataFilePath;
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{
_steps = ESteps.Website;
FileLoadPath = MainBundleInfo.Bundle.CachedDataFilePath;
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{
_steps = ESteps.CheckFile;
FileLoadPath = MainBundleInfo.Bundle.CachedDataFilePath;
}
else
{
throw new System.NotImplementedException(MainBundleInfo.LoadMode.ToString());
}
}
// 1. 下载远端文件
if (_steps == ESteps.Download)
{
int failedTryAgain = int.MaxValue;
_downloader = DownloadSystem.BeginDownload(MainBundleInfo, failedTryAgain);
_steps = ESteps.CheckDownload;
}
// 2. 检测下载结果
if (_steps == ESteps.CheckDownload)
{
DownloadProgress = _downloader.DownloadProgress;
DownloadedBytes = _downloader.DownloadedBytes;
if (_downloader.IsDone() == false)
return;
if (_downloader.HasError())
{
_steps = ESteps.Done;
Status = EStatus.Failed;
LastError = _downloader.GetLastError();
}
else
{
_steps = ESteps.CheckFile;
}
}
// 3. 从站点下载
if (_steps == ESteps.Website)
{
int failedTryAgain = 1;
var bundleInfo = PatchManifestTools.GetUnpackInfo(MainBundleInfo.Bundle);
_website = DownloadSystem.BeginDownload(bundleInfo, failedTryAgain);
_steps = ESteps.CheckWebsite;
}
// 4. 检测站点下载
if (_steps == ESteps.CheckWebsite)
{
DownloadProgress = _website.DownloadProgress;
DownloadedBytes = _website.DownloadedBytes;
if (_website.IsDone() == false)
return;
if (_website.HasError())
{
_steps = ESteps.Done;
Status = EStatus.Failed;
LastError = _website.GetLastError();
}
else
{
_steps = ESteps.CheckFile;
}
}
// 5. 检测结果
if (_steps == ESteps.CheckFile)
{
// 设置下载进度
DownloadProgress = 1f;
DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize;
_steps = ESteps.Done;
if (File.Exists(FileLoadPath))
{
Status = EStatus.Succeed;
}
else
{
Status = EStatus.Failed;
LastError = $"Raw file not found : {FileLoadPath}";
}
}
}
/// <summary>
/// 主线程等待异步操作完毕
/// </summary>
public override void WaitForAsyncComplete()
{
if (IsDone() == false)
{
Status = EStatus.Failed;
LastError = $"{nameof(WaitForAsyncComplete)} failed ! WebGL platform not support sync load method !";
YooLogger.Error(LastError);
}
}
}
}

View File

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

View File

@@ -13,7 +13,7 @@ namespace YooAsset
} }
public override void Update() public override void Update()
{ {
DebugRecording(); DebugBeginRecording();
if (IsDone) if (IsDone)
return; return;

View File

@@ -8,7 +8,7 @@ namespace YooAsset
} }
public override void Update() public override void Update()
{ {
DebugRecording(); DebugBeginRecording();
if (IsDone) if (IsDone)
return; return;

View File

@@ -23,7 +23,7 @@ namespace YooAsset
} }
public override void Update() public override void Update()
{ {
DebugRecording(); DebugBeginRecording();
if (IsDone) if (IsDone)
return; return;

View File

@@ -13,7 +13,7 @@ namespace YooAsset
} }
public override void Update() public override void Update()
{ {
DebugRecording(); DebugBeginRecording();
if (IsDone) if (IsDone)
return; return;

View File

@@ -221,6 +221,8 @@ namespace YooAsset
private TaskCompletionSource<object> _taskCompletionSource; private TaskCompletionSource<object> _taskCompletionSource;
protected void InvokeCompletion() protected void InvokeCompletion()
{ {
DebugEndRecording();
// 进度百分百完成 // 进度百分百完成
Progress = 1f; Progress = 1f;
@@ -256,8 +258,7 @@ namespace YooAsset
public long LoadingTime { protected set; get; } public long LoadingTime { protected set; get; }
// 加载耗时统计 // 加载耗时统计
private bool _isRecording = false; private Stopwatch _watch = null;
private Stopwatch _watch;
[Conditional("DEBUG")] [Conditional("DEBUG")]
public void InitSpawnDebugInfo() public void InitSpawnDebugInfo()
@@ -274,21 +275,21 @@ namespace YooAsset
} }
[Conditional("DEBUG")] [Conditional("DEBUG")]
protected void DebugRecording() protected void DebugBeginRecording()
{ {
if (_isRecording == false) if (_watch == null)
{ {
_isRecording = true;
_watch = Stopwatch.StartNew(); _watch = Stopwatch.StartNew();
} }
}
[Conditional("DEBUG")]
private void DebugEndRecording()
{
if (_watch != null) if (_watch != null)
{ {
if (IsDone) LoadingTime = _watch.ElapsedMilliseconds;
{ _watch = null;
LoadingTime = _watch.ElapsedMilliseconds;
_watch = null;
}
} }
} }
#endregion #endregion

View File

@@ -23,6 +23,15 @@ namespace YooAsset
_cachedDic.Clear(); _cachedDic.Clear();
} }
/// <summary>
/// 获取缓存文件总数
/// </summary>
public static int GetCachedFilesCount(string packageName)
{
var cache = GetOrCreateCache(packageName);
return cache.GetCachedFilesCount();
}
/// <summary> /// <summary>
/// 查询是否为验证文件 /// 查询是否为验证文件
/// </summary> /// </summary>
@@ -70,7 +79,7 @@ namespace YooAsset
/// <summary> /// <summary>
/// 验证缓存文件(子线程内操作) /// 验证缓存文件(子线程内操作)
/// </summary> /// </summary>
public static EVerifyResult VerifyingCacheFile(VerifyElement element) public static EVerifyResult VerifyingCacheFile(VerifyCacheElement element)
{ {
try try
{ {
@@ -100,15 +109,15 @@ namespace YooAsset
} }
/// <summary> /// <summary>
/// 验证下载文件 /// 验证下载文件(子线程内操作)
/// </summary> /// </summary>
public static EVerifyResult VerifyingTempFile(PatchBundle patchBundle) public static EVerifyResult VerifyingTempFile(VerifyTempElement element)
{ {
return VerifyingInternal(patchBundle.TempDataFilePath, patchBundle.FileSize, patchBundle.FileCRC, EVerifyLevel.High); return VerifyingInternal(element.TempDataFilePath, element.FileSize, element.FileCRC, EVerifyLevel.High);
} }
/// <summary> /// <summary>
/// 验证记录文件 /// 验证记录文件(主线程内操作)
/// </summary> /// </summary>
public static EVerifyResult VerifyingRecordFile(string packageName, string cacheGUID) public static EVerifyResult VerifyingRecordFile(string packageName, string cacheGUID)
{ {

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a93a516506b2b5c4492fdefe26eb1175
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,175 @@
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset
{
internal class FindCacheFilesOperation : AsyncOperationBase
{
private enum ESteps
{
None,
FindPrepare,
FindBundleFiles,
FindRawFiles,
Done,
}
private readonly string _packageName;
private float _verifyStartTime;
private IEnumerator<DirectoryInfo> _bundleFilesEnumerator = null;
private IEnumerator<DirectoryInfo> _rawFilesEnumerator = null;
private ESteps _steps = ESteps.None;
/// <summary>
/// 需要验证的元素
/// </summary>
public readonly List<VerifyCacheElement> VerifyElements = new List<VerifyCacheElement>(5000);
public FindCacheFilesOperation(string packageName)
{
_packageName = packageName;
}
internal override void Start()
{
_steps = ESteps.FindPrepare;
_verifyStartTime = UnityEngine.Time.realtimeSinceStartup;
}
internal override void Update()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.FindPrepare)
{
// BundleFiles
{
string rootPath = PersistentHelper.GetCachedBundleFileFolderPath(_packageName);
DirectoryInfo rootDirectory = new DirectoryInfo(rootPath);
if (rootDirectory.Exists)
{
var directorieInfos = rootDirectory.EnumerateDirectories();
_bundleFilesEnumerator = directorieInfos.GetEnumerator();
}
}
// RawFiles
{
string rootPath = PersistentHelper.GetCachedRawFileFolderPath(_packageName);
DirectoryInfo rootDirectory = new DirectoryInfo(rootPath);
if (rootDirectory.Exists)
{
var directorieInfos = rootDirectory.EnumerateDirectories();
_rawFilesEnumerator = directorieInfos.GetEnumerator();
}
}
_steps = ESteps.FindBundleFiles;
}
if (_steps == ESteps.FindBundleFiles)
{
if (UpdateFindBundleFiles())
return;
_steps = ESteps.FindRawFiles;
}
if (_steps == ESteps.FindRawFiles)
{
if (UpdateFindRawFiles())
return;
// 注意:总是返回成功
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
float costTime = UnityEngine.Time.realtimeSinceStartup - _verifyStartTime;
YooLogger.Log($"Find cache files elapsed time {costTime:f1} seconds");
}
}
private bool UpdateFindBundleFiles()
{
if (_bundleFilesEnumerator == null)
return false;
bool isFindItem;
while (true)
{
isFindItem = _bundleFilesEnumerator.MoveNext();
if (isFindItem == false)
break;
var rootFoder = _bundleFilesEnumerator.Current;
var childDirectories = rootFoder.GetDirectories();
foreach(var chidDirectory in childDirectories)
{
string cacheGUID = chidDirectory.Name;
if (CacheSystem.IsCached(_packageName, cacheGUID))
continue;
// 创建验证元素类
string fileRootPath = chidDirectory.FullName;
string dataFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleDataFileName}";
string infoFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleInfoFileName}";
VerifyCacheElement element = new VerifyCacheElement(_packageName, cacheGUID, fileRootPath, dataFilePath, infoFilePath);
VerifyElements.Add(element);
}
if (OperationSystem.IsBusy)
break;
}
return isFindItem;
}
private bool UpdateFindRawFiles()
{
if (_rawFilesEnumerator == null)
return false;
bool isFindItem;
while (true)
{
isFindItem = _rawFilesEnumerator.MoveNext();
if (isFindItem == false)
break;
var rootFoder = _rawFilesEnumerator.Current;
var childDirectories = rootFoder.GetDirectories();
foreach (var chidDirectory in childDirectories)
{
string cacheGUID = chidDirectory.Name;
if (CacheSystem.IsCached(_packageName, cacheGUID))
continue;
// 获取数据文件的后缀名
string dataFileExtension = string.Empty;
var fileInfos = chidDirectory.GetFiles();
foreach (var fileInfo in fileInfos)
{
if (fileInfo.Extension == ".temp")
continue;
if (fileInfo.Name.StartsWith(YooAssetSettings.CacheBundleDataFileName))
{
dataFileExtension = fileInfo.Extension;
break;
}
}
// 创建验证元素类
string fileRootPath = chidDirectory.FullName;
string dataFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleDataFileName}{dataFileExtension}";
string infoFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleInfoFileName}";
VerifyCacheElement element = new VerifyCacheElement(_packageName, cacheGUID, fileRootPath, dataFilePath, infoFilePath);
VerifyElements.Add(element);
}
if (OperationSystem.IsBusy)
break;
}
return isFindItem;
}
}
}

View File

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

View File

@@ -6,14 +6,14 @@ using System.Threading;
namespace YooAsset namespace YooAsset
{ {
internal abstract class PackageVerifyOperation : AsyncOperationBase internal abstract class VerifyCacheFilesOperation : AsyncOperationBase
{ {
public static PackageVerifyOperation CreateOperation(List<VerifyElement> elements) public static VerifyCacheFilesOperation CreateOperation(List<VerifyCacheElement> elements)
{ {
#if UNITY_WEBGL #if UNITY_WEBGL
var operation = new PackageVerifyWithoutThreadOperation(elements); var operation = new VerifyCacheFilesWithoutThreadOperation(elements);
#else #else
var operation = new PackageVerifyWithThreadOperation(elements); var operation = new VerifyCacheFilesWithThreadOperation(elements);
#endif #endif
return operation; return operation;
} }
@@ -22,7 +22,7 @@ namespace YooAsset
/// <summary> /// <summary>
/// 本地缓存文件验证(线程版) /// 本地缓存文件验证(线程版)
/// </summary> /// </summary>
internal class PackageVerifyWithThreadOperation : PackageVerifyOperation internal class VerifyCacheFilesWithThreadOperation : VerifyCacheFilesOperation
{ {
private enum ESteps private enum ESteps
{ {
@@ -33,8 +33,8 @@ namespace YooAsset
} }
private readonly ThreadSyncContext _syncContext = new ThreadSyncContext(); private readonly ThreadSyncContext _syncContext = new ThreadSyncContext();
private List<VerifyElement> _waitingList; private List<VerifyCacheElement> _waitingList;
private List<VerifyElement> _verifyingList; private List<VerifyCacheElement> _verifyingList;
private int _verifyMaxNum; private int _verifyMaxNum;
private int _verifyTotalCount; private int _verifyTotalCount;
private float _verifyStartTime; private float _verifyStartTime;
@@ -42,7 +42,7 @@ namespace YooAsset
private int _failedCount; private int _failedCount;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
public PackageVerifyWithThreadOperation(List<VerifyElement> elements) public VerifyCacheFilesWithThreadOperation(List<VerifyCacheElement> elements)
{ {
_waitingList = elements; _waitingList = elements;
} }
@@ -68,7 +68,7 @@ namespace YooAsset
if (_verifyMaxNum < 1) if (_verifyMaxNum < 1)
_verifyMaxNum = 1; _verifyMaxNum = 1;
_verifyingList = new List<VerifyElement>(_verifyMaxNum); _verifyingList = new List<VerifyCacheElement>(_verifyMaxNum);
_steps = ESteps.UpdateVerify; _steps = ESteps.UpdateVerify;
} }
@@ -82,7 +82,7 @@ namespace YooAsset
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
float costTime = UnityEngine.Time.realtimeSinceStartup - _verifyStartTime; float costTime = UnityEngine.Time.realtimeSinceStartup - _verifyStartTime;
YooLogger.Log($"Package verify elapsed time {costTime:f1} seconds"); YooLogger.Log($"Verify cache files elapsed time {costTime:f1} seconds");
} }
for (int i = _waitingList.Count - 1; i >= 0; i--) for (int i = _waitingList.Count - 1; i >= 0; i--)
@@ -114,19 +114,19 @@ namespace YooAsset
return 1f; return 1f;
return (float)(_succeedCount + _failedCount) / _verifyTotalCount; return (float)(_succeedCount + _failedCount) / _verifyTotalCount;
} }
private bool BeginVerifyFileWithThread(VerifyElement element) private bool BeginVerifyFileWithThread(VerifyCacheElement element)
{ {
return ThreadPool.QueueUserWorkItem(new WaitCallback(VerifyInThread), element); return ThreadPool.QueueUserWorkItem(new WaitCallback(VerifyInThread), element);
} }
private void VerifyInThread(object obj) private void VerifyInThread(object obj)
{ {
VerifyElement element = (VerifyElement)obj; VerifyCacheElement element = (VerifyCacheElement)obj;
element.Result = CacheSystem.VerifyingCacheFile(element); element.Result = CacheSystem.VerifyingCacheFile(element);
_syncContext.Post(VerifyCallback, element); _syncContext.Post(VerifyCallback, element);
} }
private void VerifyCallback(object obj) private void VerifyCallback(object obj)
{ {
VerifyElement element = (VerifyElement)obj; VerifyCacheElement element = (VerifyCacheElement)obj;
_verifyingList.Remove(element); _verifyingList.Remove(element);
if (element.Result == EVerifyResult.Succeed) if (element.Result == EVerifyResult.Succeed)
@@ -148,7 +148,7 @@ namespace YooAsset
/// <summary> /// <summary>
/// 本地缓存文件验证(非线程版) /// 本地缓存文件验证(非线程版)
/// </summary> /// </summary>
internal class PackageVerifyWithoutThreadOperation : PackageVerifyOperation internal class VerifyCacheFilesWithoutThreadOperation : VerifyCacheFilesOperation
{ {
private enum ESteps private enum ESteps
{ {
@@ -158,16 +158,16 @@ namespace YooAsset
Done, Done,
} }
private List<VerifyElement> _waitingList; private List<VerifyCacheElement> _waitingList;
private List<VerifyElement> _verifyingList; private List<VerifyCacheElement> _verifyingList;
private int _verifyMaxNum; private int _verifyMaxNum;
private int _verifyTotalCount; private int _verifyTotalCount;
private float _verifyStartTime; private float _verifyStartTime;
private int _succeedCount; private int _succeedCount;
private int _failedCount; private int _failedCount;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
public PackageVerifyWithoutThreadOperation(List<VerifyElement> elements) public VerifyCacheFilesWithoutThreadOperation(List<VerifyCacheElement> elements)
{ {
_waitingList = elements; _waitingList = elements;
} }
@@ -189,7 +189,7 @@ namespace YooAsset
_verifyMaxNum = fileCount; _verifyMaxNum = fileCount;
_verifyTotalCount = fileCount; _verifyTotalCount = fileCount;
_verifyingList = new List<VerifyElement>(_verifyMaxNum); _verifyingList = new List<VerifyCacheElement>(_verifyMaxNum);
_steps = ESteps.UpdateVerify; _steps = ESteps.UpdateVerify;
} }
@@ -229,7 +229,7 @@ namespace YooAsset
return 1f; return 1f;
return (float)(_succeedCount + _failedCount) / _verifyTotalCount; return (float)(_succeedCount + _failedCount) / _verifyTotalCount;
} }
private void BeginVerifyFileWithoutThread(VerifyElement element) private void BeginVerifyFileWithoutThread(VerifyCacheElement element)
{ {
element.Result = CacheSystem.VerifyingCacheFile(element); element.Result = CacheSystem.VerifyingCacheFile(element);
if (element.Result == EVerifyResult.Succeed) if (element.Result == EVerifyResult.Succeed)

View File

@@ -0,0 +1,141 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
namespace YooAsset
{
internal abstract class VerifyTempFileOperation : AsyncOperationBase
{
public EVerifyResult VerifyResult { protected set; get; }
public static VerifyTempFileOperation CreateOperation(VerifyTempElement element)
{
#if UNITY_WEBGL
var operation = new VerifyTempFileWithoutThreadOperation(element);
#else
var operation = new VerifyTempFileWithThreadOperation(element);
#endif
return operation;
}
}
/// <summary>
/// 下载文件验证(线程版)
/// </summary>
internal class VerifyTempFileWithThreadOperation : VerifyTempFileOperation
{
private enum ESteps
{
None,
VerifyFile,
Waiting,
Done,
}
private readonly VerifyTempElement _element;
private ESteps _steps = ESteps.None;
public VerifyTempFileWithThreadOperation(VerifyTempElement element)
{
_element = element;
}
internal override void Start()
{
_steps = ESteps.VerifyFile;
}
internal override void Update()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.VerifyFile)
{
if (BeginVerifyFileWithThread(_element))
{
_steps = ESteps.Waiting;
}
}
if (_steps == ESteps.Waiting)
{
if (_element.IsDone == false)
return;
VerifyResult = _element.Result;
if (_element.Result == EVerifyResult.Succeed)
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Failed verify file : {_element.TempDataFilePath} ! ErrorCode : {_element.Result}";
}
}
}
private bool BeginVerifyFileWithThread(VerifyTempElement element)
{
return ThreadPool.QueueUserWorkItem(new WaitCallback(VerifyInThread), element);
}
private void VerifyInThread(object obj)
{
VerifyTempElement element = (VerifyTempElement)obj;
element.Result = CacheSystem.VerifyingTempFile(element);
element.IsDone = true;
}
}
/// <summary>
/// 下载文件验证(非线程版)
/// </summary>
internal class VerifyTempFileWithoutThreadOperation : VerifyTempFileOperation
{
private enum ESteps
{
None,
VerifyFile,
Done,
}
private readonly VerifyTempElement _element;
private ESteps _steps = ESteps.None;
public VerifyTempFileWithoutThreadOperation(VerifyTempElement element)
{
_element = element;
}
internal override void Start()
{
_steps = ESteps.VerifyFile;
}
internal override void Update()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.VerifyFile)
{
_element.Result = CacheSystem.VerifyingTempFile(_element);
_element.IsDone = true;
VerifyResult = _element.Result;
if (_element.Result == EVerifyResult.Succeed)
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Failed verify file : {_element.TempDataFilePath} ! ErrorCode : {_element.Result}";
}
}
}
}
}

View File

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

View File

@@ -10,13 +10,14 @@ namespace YooAsset
private enum ESteps private enum ESteps
{ {
None, None,
GetCacheFiles, FindCacheFiles,
VerifyCacheFiles, VerifyCacheFiles,
Done, Done,
} }
private readonly string _packageName; private readonly string _packageName;
private PackageVerifyOperation _packageVerifyOp; private FindCacheFilesOperation _findCacheFilesOp;
private VerifyCacheFilesOperation _verifyCacheFilesOp;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
public PackageCachingOperation(string packageName) public PackageCachingOperation(string packageName)
@@ -25,71 +26,47 @@ namespace YooAsset
} }
internal override void Start() internal override void Start()
{ {
_steps = ESteps.GetCacheFiles; _steps = ESteps.FindCacheFiles;
} }
internal override void Update() internal override void Update()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.GetCacheFiles) if (_steps == ESteps.FindCacheFiles)
{ {
var elements = GetVerifyElements(); if (_findCacheFilesOp == null)
_packageVerifyOp = PackageVerifyOperation.CreateOperation(elements); {
OperationSystem.StartOperation(_packageVerifyOp); _findCacheFilesOp = new FindCacheFilesOperation(_packageName);
OperationSystem.StartOperation(_findCacheFilesOp);
}
Progress = _findCacheFilesOp.Progress;
if (_findCacheFilesOp.IsDone == false)
return;
_steps = ESteps.VerifyCacheFiles; _steps = ESteps.VerifyCacheFiles;
} }
if (_steps == ESteps.VerifyCacheFiles) if (_steps == ESteps.VerifyCacheFiles)
{ {
Progress = _packageVerifyOp.Progress; if (_verifyCacheFilesOp == null)
if (_packageVerifyOp.IsDone == false) {
_verifyCacheFilesOp = VerifyCacheFilesOperation.CreateOperation(_findCacheFilesOp.VerifyElements);
OperationSystem.StartOperation(_verifyCacheFilesOp);
}
Progress = _verifyCacheFilesOp.Progress;
if (_verifyCacheFilesOp.IsDone == false)
return; return;
// 注意:总是返回成功 // 注意:总是返回成功
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
int totalCount = CacheSystem.GetCachedFilesCount(_packageName);
YooLogger.Log($"Package '{_packageName}' cached files count : {totalCount}");
} }
} }
private List<VerifyElement> GetVerifyElements()
{
string cacheFolderPath = PersistentHelper.GetCacheFolderPath(_packageName);
if (Directory.Exists(cacheFolderPath) == false)
return new List<VerifyElement>();
DirectoryInfo rootDirectory = new DirectoryInfo(cacheFolderPath);
DirectoryInfo[] fileFolders = rootDirectory.GetDirectories();
List<VerifyElement> result = new List<VerifyElement>(fileFolders.Length);
foreach (var fileFoder in fileFolders)
{
string cacheGUID = fileFoder.Name;
if (CacheSystem.IsCached(_packageName, cacheGUID))
continue;
// 获取数据文件的后缀名
string dataFileExtension = string.Empty;
var fileInfos = fileFoder.GetFiles();
foreach (var fileInfo in fileInfos)
{
if (fileInfo.Extension == ".temp")
continue;
if (fileInfo.Name.StartsWith(YooAssetSettings.CacheBundleDataFileName))
{
dataFileExtension = fileInfo.Extension;
break;
}
}
string fileRootPath = fileFoder.FullName;
string dataFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleDataFileName}{dataFileExtension}";
string infoFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleInfoFileName}";
VerifyElement element = new VerifyElement(_packageName, cacheGUID, fileRootPath, dataFilePath, infoFilePath);
result.Add(element);
}
return result;
}
} }
} }

View File

@@ -44,6 +44,14 @@ namespace YooAsset
_wrappers.Clear(); _wrappers.Clear();
} }
/// <summary>
/// 获取缓存文件总数
/// </summary>
public int GetCachedFilesCount()
{
return _wrappers.Count;
}
/// <summary> /// <summary>
/// 查询缓存记录 /// 查询缓存记录
/// </summary> /// </summary>

View File

@@ -2,19 +2,22 @@
namespace YooAsset namespace YooAsset
{ {
internal class VerifyElement /// <summary>
/// 缓存文件验证元素
/// </summary>
internal class VerifyCacheElement
{ {
public string PackageName { private set; get; } public string PackageName { private set; get; }
public string CacheGUID { private set; get; } public string CacheGUID { private set; get; }
public string FileRootPath { private set; get; } public string FileRootPath { private set; get; }
public string DataFilePath { private set; get; } public string DataFilePath { private set; get; }
public string InfoFilePath { private set; get; } public string InfoFilePath { private set; get; }
public EVerifyResult Result; public EVerifyResult Result;
public string DataFileCRC; public string DataFileCRC;
public long DataFileSize; public long DataFileSize;
public VerifyElement(string packageName, string cacheGUID, string fileRootPath, string dataFilePath, string infoFilePath) public VerifyCacheElement(string packageName, string cacheGUID, string fileRootPath, string dataFilePath, string infoFilePath)
{ {
PackageName = packageName; PackageName = packageName;
CacheGUID = cacheGUID; CacheGUID = cacheGUID;
@@ -36,4 +39,24 @@ namespace YooAsset
} }
} }
} }
/// <summary>
/// 下载文件验证元素
/// </summary>
internal class VerifyTempElement
{
public string TempDataFilePath { private set; get; }
public string FileCRC { private set; get; }
public long FileSize { private set; get; }
public bool IsDone = false;
public EVerifyResult Result;
public VerifyTempElement(string tempDataFilePath, string fileCRC, long fileSize)
{
TempDataFilePath = tempDataFilePath;
FileCRC = fileCRC;
FileSize = fileSize;
}
}
} }

View File

@@ -2,10 +2,16 @@
using System.IO; using System.IO;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading;
using UnityEngine.Networking; using UnityEngine.Networking;
namespace YooAsset namespace YooAsset
{ {
/// <summary>
/// 自定义下载器的请求委托
/// </summary>
public delegate UnityWebRequest DownloadRequestDelegate(string url);
/// <summary> /// <summary>
/// 1. 保证每一时刻资源文件只存在一个下载器 /// 1. 保证每一时刻资源文件只存在一个下载器
/// 2. 保证下载器下载完成后立刻验证并缓存 /// 2. 保证下载器下载完成后立刻验证并缓存
@@ -16,11 +22,15 @@ namespace YooAsset
private static readonly Dictionary<string, DownloaderBase> _downloaderDic = new Dictionary<string, DownloaderBase>(); private static readonly Dictionary<string, DownloaderBase> _downloaderDic = new Dictionary<string, DownloaderBase>();
private static readonly List<string> _removeList = new List<string>(100); private static readonly List<string> _removeList = new List<string>(100);
/// <summary>
/// 自定义下载器的请求委托
/// </summary>
public static DownloadRequestDelegate RequestDelegate = null;
/// <summary> /// <summary>
/// 自定义的证书认证实例 /// 自定义的证书认证实例
/// </summary> /// </summary>
public static CertificateHandler CertificateHandlerInstance; public static CertificateHandler CertificateHandlerInstance = null;
/// <summary> /// <summary>
/// 启用断点续传功能文件的最小字节数 /// 启用断点续传功能文件的最小字节数
@@ -32,8 +42,16 @@ namespace YooAsset
/// </summary> /// </summary>
public static List<long> ClearFileResponseCodes { set; get; } public static List<long> ClearFileResponseCodes { set; get; }
/// <summary> /// <summary>
/// 更新所有下载器 /// 初始化下载器
/// </summary>
public static void Initialize()
{
}
/// <summary>
/// 更新下载器
/// </summary> /// </summary>
public static void Update() public static void Update()
{ {
@@ -66,7 +84,11 @@ namespace YooAsset
} }
_downloaderDic.Clear(); _downloaderDic.Clear();
_removeList.Clear(); _removeList.Clear();
RequestDelegate = null;
CertificateHandlerInstance = null;
BreakpointResumeFileSize = int.MaxValue; BreakpointResumeFileSize = int.MaxValue;
ClearFileResponseCodes = null;
} }
@@ -101,6 +123,18 @@ namespace YooAsset
} }
} }
/// <summary>
/// 创建一个新的网络请求
/// </summary>
public static UnityWebRequest NewRequest(string requestURL)
{
if (RequestDelegate != null)
return RequestDelegate.Invoke(requestURL);
var request = new UnityWebRequest(requestURL, UnityWebRequest.kHttpVerbGET);
return request;
}
/// <summary> /// <summary>
/// 获取下载器的总数 /// 获取下载器的总数
/// </summary> /// </summary>

View File

@@ -7,11 +7,13 @@ namespace YooAsset
{ {
None, None,
CheckTempFile, CheckTempFile,
WaitingCheckTempFile,
PrepareDownload, PrepareDownload,
CreateResumeDownloader, CreateResumeDownloader,
CreateGeneralDownloader, CreateGeneralDownloader,
CheckDownload, CheckDownload,
VerifyingFile, VerifyTempFile,
WaitingVerifyTempFile,
CachingFile, CachingFile,
TryAgain, TryAgain,
Succeed, Succeed,
@@ -32,6 +34,11 @@ namespace YooAsset
protected float _downloadProgress = 0f; protected float _downloadProgress = 0f;
protected ulong _downloadedBytes = 0; protected ulong _downloadedBytes = 0;
/// <summary>
/// 是否等待异步结束
/// 警告只能用于解压APP内部资源
/// </summary>
public bool WaitForAsyncComplete = false;
/// <summary> /// <summary>
/// 下载进度0f~1f /// 下载进度0f~1f

View File

@@ -13,6 +13,8 @@ namespace YooAsset
private readonly string _tempFilePath; private readonly string _tempFilePath;
private UnityWebRequest _webRequest = null; private UnityWebRequest _webRequest = null;
private DownloadHandlerFileRange _downloadHandle = null; private DownloadHandlerFileRange _downloadHandle = null;
private VerifyTempFileOperation _checkFileOp = null;
private VerifyTempFileOperation _verifyFileOp = null;
// 重置变量 // 重置变量
private bool _isAbort = false; private bool _isAbort = false;
@@ -34,17 +36,31 @@ namespace YooAsset
if (IsDone()) if (IsDone())
return; return;
// 检测本地临时文件 // 检测临时文件
if (_steps == ESteps.CheckTempFile) if (_steps == ESteps.CheckTempFile)
{ {
var verifyResult = CacheSystem.VerifyingTempFile(_bundleInfo.Bundle); VerifyTempElement element = new VerifyTempElement(_bundleInfo.Bundle.TempDataFilePath, _bundleInfo.Bundle.FileCRC, _bundleInfo.Bundle.FileSize);
if (verifyResult == EVerifyResult.Succeed) _checkFileOp = VerifyTempFileOperation.CreateOperation(element);
OperationSystem.StartOperation(_checkFileOp);
_steps = ESteps.WaitingCheckTempFile;
}
// 等待检测结果
if (_steps == ESteps.WaitingCheckTempFile)
{
if (WaitForAsyncComplete)
_checkFileOp.Update();
if (_checkFileOp.IsDone == false)
return;
if (_checkFileOp.Status == EOperationStatus.Succeed)
{ {
_steps = ESteps.CachingFile; _steps = ESteps.CachingFile;
} }
else else
{ {
if (verifyResult == EVerifyResult.FileOverflow) if (_checkFileOp.VerifyResult == EVerifyResult.FileOverflow)
{ {
if (File.Exists(_tempFilePath)) if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath); File.Delete(_tempFilePath);
@@ -80,7 +96,7 @@ namespace YooAsset
if (File.Exists(_tempFilePath)) if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath); File.Delete(_tempFilePath);
_webRequest = new UnityWebRequest(_requestURL, UnityWebRequest.kHttpVerbGET); _webRequest = DownloadSystem.NewRequest(_requestURL);
DownloadHandlerFile handler = new DownloadHandlerFile(_tempFilePath); DownloadHandlerFile handler = new DownloadHandlerFile(_tempFilePath);
handler.removeFileOnAbort = true; handler.removeFileOnAbort = true;
_webRequest.downloadHandler = handler; _webRequest.downloadHandler = handler;
@@ -109,11 +125,11 @@ namespace YooAsset
} }
#if UNITY_2019_4_OR_NEWER #if UNITY_2019_4_OR_NEWER
_webRequest = new UnityWebRequest(_requestURL, UnityWebRequest.kHttpVerbGET); _webRequest = DownloadSystem.NewRequest(_requestURL);
var handler = new DownloadHandlerFile(_tempFilePath, true); var handler = new DownloadHandlerFile(_tempFilePath, true);
handler.removeFileOnAbort = false; handler.removeFileOnAbort = false;
#else #else
_webRequest = new UnityWebRequest(_requestURL, UnityWebRequest.kHttpVerbGET); _webRequest = DownloadSystem.NewRequest(_requestURL);
var handler = new DownloadHandlerFileRange(_tempFilePath, _bundleInfo.Bundle.FileSize, _webRequest); var handler = new DownloadHandlerFileRange(_tempFilePath, _bundleInfo.Bundle.FileSize, _webRequest);
_downloadHandle = handler; _downloadHandle = handler;
#endif #endif
@@ -188,7 +204,7 @@ namespace YooAsset
} }
else else
{ {
_steps = ESteps.VerifyingFile; _steps = ESteps.VerifyTempFile;
} }
// 释放下载器 // 释放下载器
@@ -196,21 +212,33 @@ namespace YooAsset
} }
// 验证下载文件 // 验证下载文件
if (_steps == ESteps.VerifyingFile) if (_steps == ESteps.VerifyTempFile)
{ {
var verifyResult = CacheSystem.VerifyingTempFile(_bundleInfo.Bundle); VerifyTempElement element = new VerifyTempElement(_bundleInfo.Bundle.TempDataFilePath, _bundleInfo.Bundle.FileCRC, _bundleInfo.Bundle.FileSize);
if (verifyResult == EVerifyResult.Succeed) _verifyFileOp = VerifyTempFileOperation.CreateOperation(element);
OperationSystem.StartOperation(_verifyFileOp);
_steps = ESteps.WaitingVerifyTempFile;
}
// 等待验证完成
if (_steps == ESteps.WaitingVerifyTempFile)
{
if (WaitForAsyncComplete)
_verifyFileOp.Update();
if (_verifyFileOp.IsDone == false)
return;
if (_verifyFileOp.Status == EOperationStatus.Succeed)
{ {
_steps = ESteps.CachingFile; _steps = ESteps.CachingFile;
} }
else else
{ {
_lastError = $"Failed to verifying file : {_bundleInfo.Bundle.FileName}, ErrorCode : {verifyResult}";
// 注意:验证失败后删除文件
if (File.Exists(_tempFilePath)) if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath); File.Delete(_tempFilePath);
_lastError = _verifyFileOp.Error;
_steps = ESteps.TryAgain; _steps = ESteps.TryAgain;
} }
} }
@@ -226,7 +254,7 @@ namespace YooAsset
long dataFileSize = _bundleInfo.Bundle.FileSize; long dataFileSize = _bundleInfo.Bundle.FileSize;
if (File.Exists(infoFilePath)) if (File.Exists(infoFilePath))
File.Delete(infoFilePath); File.Delete(infoFilePath);
if (File.Exists(dataFilePath)) if (File.Exists(dataFilePath))
File.Delete(dataFilePath); File.Delete(dataFilePath);

View File

@@ -29,7 +29,7 @@ namespace YooAsset
if (_webRequest == null) if (_webRequest == null)
{ {
URL = url; URL = url;
_webRequest = new UnityWebRequest(URL, UnityWebRequest.kHttpVerbGET); _webRequest = DownloadSystem.NewRequest(URL);
DownloadHandlerBuffer handler = new DownloadHandlerBuffer(); DownloadHandlerBuffer handler = new DownloadHandlerBuffer();
_webRequest.downloadHandler = handler; _webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true; _webRequest.disposeDownloadHandlerOnDispose = true;

View File

@@ -39,7 +39,7 @@ namespace YooAsset
_latestDownloadBytes = 0; _latestDownloadBytes = 0;
_latestDownloadRealtime = Time.realtimeSinceStartup; _latestDownloadRealtime = Time.realtimeSinceStartup;
_webRequest = new UnityWebRequest(URL, UnityWebRequest.kHttpVerbGET); _webRequest = DownloadSystem.NewRequest(URL);
DownloadHandlerFile handler = new DownloadHandlerFile(savePath); DownloadHandlerFile handler = new DownloadHandlerFile(savePath);
handler.removeFileOnAbort = true; handler.removeFileOnAbort = true;
_webRequest.downloadHandler = handler; _webRequest.downloadHandler = handler;

View File

@@ -6,6 +6,17 @@ namespace YooAsset
private readonly PatchAsset _patchAsset; private readonly PatchAsset _patchAsset;
private string _providerGUID; private string _providerGUID;
/// <summary>
/// 资源类型
/// </summary>
public System.Type AssetType { private set; get; }
/// <summary>
/// 错误信息
/// </summary>
public string Error { private set; get; }
/// <summary> /// <summary>
/// 唯一标识符 /// 唯一标识符
/// </summary> /// </summary>
@@ -35,40 +46,45 @@ namespace YooAsset
} }
} }
/// <summary>
/// 错误信息
/// </summary>
internal string Error { private set; get; }
/// <summary> /// <summary>
/// 可寻址地址 /// 可寻址地址
/// </summary> /// </summary>
public string Address { private set; get; } public string Address
{
get
{
if (_patchAsset == null)
return string.Empty;
return _patchAsset.Address;
}
}
/// <summary> /// <summary>
/// 资源路径 /// 资源路径
/// </summary> /// </summary>
public string AssetPath { private set; get; } public string AssetPath
{
/// <summary> get
/// 资源类型 {
/// </summary> if (_patchAsset == null)
public System.Type AssetType { private set; get; } return string.Empty;
return _patchAsset.AssetPath;
}
}
// 注意:这是一个内部类,严格限制外部创建。
private AssetInfo() private AssetInfo()
{ {
// 注意:禁止从外部创建该类
} }
internal AssetInfo(PatchAsset patchAsset, System.Type assetType) internal AssetInfo(PatchAsset patchAsset, System.Type assetType)
{ {
if (patchAsset == null) if (patchAsset == null)
throw new System.Exception("Should never get here !"); throw new System.Exception("Should never get here !");
_providerGUID = string.Empty;
_patchAsset = patchAsset; _patchAsset = patchAsset;
AssetType = assetType; AssetType = assetType;
Address = patchAsset.Address;
AssetPath = patchAsset.AssetPath;
Error = string.Empty; Error = string.Empty;
} }
internal AssetInfo(PatchAsset patchAsset) internal AssetInfo(PatchAsset patchAsset)
@@ -76,18 +92,16 @@ namespace YooAsset
if (patchAsset == null) if (patchAsset == null)
throw new System.Exception("Should never get here !"); throw new System.Exception("Should never get here !");
_providerGUID = string.Empty;
_patchAsset = patchAsset; _patchAsset = patchAsset;
AssetType = null; AssetType = null;
Address = patchAsset.Address;
AssetPath = patchAsset.AssetPath;
Error = string.Empty; Error = string.Empty;
} }
internal AssetInfo(string error) internal AssetInfo(string error)
{ {
_providerGUID = string.Empty;
_patchAsset = null; _patchAsset = null;
AssetType = null; AssetType = null;
Address = string.Empty;
AssetPath = string.Empty;
Error = error; Error = error;
} }
} }

View File

@@ -32,28 +32,36 @@ namespace YooAsset
private bool _isPause = false; private bool _isPause = false;
private long _lastDownloadBytes = 0; private long _lastDownloadBytes = 0;
private int _lastDownloadCount = 0; private int _lastDownloadCount = 0;
private long _cachedDownloadBytes = 0;
private int _cachedDownloadCount = 0;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
/// <summary> /// <summary>
/// 下载文件总数量 /// 统计的下载文件总数量
/// </summary> /// </summary>
public int TotalDownloadCount { private set; get; } public int TotalDownloadCount { private set; get; }
/// <summary> /// <summary>
/// 下载文件的总大小 /// 统计的下载文件的总大小
/// </summary> /// </summary>
public long TotalDownloadBytes { private set; get; } public long TotalDownloadBytes { private set; get; }
/// <summary> /// <summary>
/// 当前已经完成的下载总数量 /// 当前已经完成的下载总数量
/// </summary> /// </summary>
public int CurrentDownloadCount { private set; get; } public int CurrentDownloadCount
{
get { return _lastDownloadCount; }
}
/// <summary> /// <summary>
/// 当前已经完成的下载总大小 /// 当前已经完成的下载总大小
/// </summary> /// </summary>
public long CurrentDownloadBytes { private set; get; } public long CurrentDownloadBytes
{
get { return _lastDownloadBytes; }
}
/// <summary> /// <summary>
/// 当下载器结束(无论成功或失败) /// 当下载器结束(无论成功或失败)
@@ -120,7 +128,7 @@ namespace YooAsset
{ {
// 检测下载器结果 // 检测下载器结果
_removeList.Clear(); _removeList.Clear();
long downloadBytes = CurrentDownloadBytes; long downloadBytes = _cachedDownloadBytes;
foreach (var downloader in _downloaders) foreach (var downloader in _downloaders)
{ {
downloadBytes += (long)downloader.DownloadedBytes; downloadBytes += (long)downloader.DownloadedBytes;
@@ -139,8 +147,8 @@ namespace YooAsset
// 下载成功 // 下载成功
_removeList.Add(downloader); _removeList.Add(downloader);
CurrentDownloadCount++; _cachedDownloadCount++;
CurrentDownloadBytes += bundleInfo.Bundle.FileSize; _cachedDownloadBytes += bundleInfo.Bundle.FileSize;
} }
// 移除已经完成的下载器(无论成功或失败) // 移除已经完成的下载器(无论成功或失败)
@@ -150,10 +158,10 @@ namespace YooAsset
} }
// 如果下载进度发生变化 // 如果下载进度发生变化
if (_lastDownloadBytes != downloadBytes || _lastDownloadCount != CurrentDownloadCount) if (_lastDownloadBytes != downloadBytes || _lastDownloadCount != _cachedDownloadCount)
{ {
_lastDownloadBytes = downloadBytes; _lastDownloadBytes = downloadBytes;
_lastDownloadCount = CurrentDownloadCount; _lastDownloadCount = _cachedDownloadCount;
Progress = (float)_lastDownloadBytes / TotalDownloadBytes; Progress = (float)_lastDownloadBytes / TotalDownloadBytes;
OnDownloadProgressCallback?.Invoke(TotalDownloadCount, _lastDownloadCount, TotalDownloadBytes, _lastDownloadBytes); OnDownloadProgressCallback?.Invoke(TotalDownloadCount, _lastDownloadCount, TotalDownloadBytes, _lastDownloadBytes);
} }

View File

@@ -46,7 +46,7 @@ namespace YooAsset
/// </summary> /// </summary>
public int[] ReferenceIDs; public int[] ReferenceIDs;
/// <summary> /// <summary>
/// 所属的包裹名称 /// 所属的包裹名称
/// </summary> /// </summary>
@@ -71,8 +71,17 @@ namespace YooAsset
if (string.IsNullOrEmpty(_cachedDataFilePath) == false) if (string.IsNullOrEmpty(_cachedDataFilePath) == false)
return _cachedDataFilePath; return _cachedDataFilePath;
string cacheRoot = PersistentHelper.GetCacheFolderPath(PackageName); string folderName = FileHash.Substring(0, 2);
_cachedDataFilePath = $"{cacheRoot}/{CacheGUID}/{YooAssetSettings.CacheBundleDataFileName}{_fileExtension}"; if (IsRawFile)
{
string cacheRoot = PersistentHelper.GetCachedRawFileFolderPath(PackageName);
_cachedDataFilePath = $"{cacheRoot}/{folderName}/{CacheGUID}/{YooAssetSettings.CacheBundleDataFileName}{_fileExtension}";
}
else
{
string cacheRoot = PersistentHelper.GetCachedBundleFileFolderPath(PackageName);
_cachedDataFilePath = $"{cacheRoot}/{folderName}/{CacheGUID}/{YooAssetSettings.CacheBundleDataFileName}";
}
return _cachedDataFilePath; return _cachedDataFilePath;
} }
} }
@@ -88,8 +97,17 @@ namespace YooAsset
if (string.IsNullOrEmpty(_cachedInfoFilePath) == false) if (string.IsNullOrEmpty(_cachedInfoFilePath) == false)
return _cachedInfoFilePath; return _cachedInfoFilePath;
string cacheRoot = PersistentHelper.GetCacheFolderPath(PackageName); string folderName = FileHash.Substring(0, 2);
_cachedInfoFilePath = $"{cacheRoot}/{CacheGUID}/{YooAssetSettings.CacheBundleInfoFileName}"; if (IsRawFile)
{
string cacheRoot = PersistentHelper.GetCachedRawFileFolderPath(PackageName);
_cachedInfoFilePath = $"{cacheRoot}/{folderName}/{CacheGUID}/{YooAssetSettings.CacheBundleInfoFileName}";
}
else
{
string cacheRoot = PersistentHelper.GetCachedBundleFileFolderPath(PackageName);
_cachedInfoFilePath = $"{cacheRoot}/{folderName}/{CacheGUID}/{YooAssetSettings.CacheBundleInfoFileName}";
}
return _cachedInfoFilePath; return _cachedInfoFilePath;
} }
} }

View File

@@ -32,7 +32,7 @@ namespace YooAsset
/// <summary> /// <summary>
/// 文件流解密方法 /// 文件流解密方法
/// </summary> /// </summary>
System.IO.FileStream LoadFromStream(DecryptFileInfo fileInfo); System.IO.Stream LoadFromStream(DecryptFileInfo fileInfo);
/// <summary> /// <summary>
/// 文件流解密的托管缓存大小 /// 文件流解密的托管缓存大小

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 40c870edb8e84064a8be2d56acb8bbc0
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -84,6 +84,8 @@ namespace YooAsset
internal static class PersistentHelper internal static class PersistentHelper
{ {
private const string CacheFolderName = "CacheFiles"; private const string CacheFolderName = "CacheFiles";
private const string CachedBundleFileFolder = "BundleFiles";
private const string CachedRawFileFolder = "RawFiles";
private const string ManifestFolderName = "ManifestFiles"; private const string ManifestFolderName = "ManifestFiles";
private const string AppFootPrintFileName = "ApplicationFootPrint.bytes"; private const string AppFootPrintFileName = "ApplicationFootPrint.bytes";
@@ -120,12 +122,33 @@ namespace YooAsset
/// <summary> /// <summary>
/// 获取缓存文件夹路径 /// 获取缓存的BundleFile文件夹路径
/// </summary> /// </summary>
public static string GetCacheFolderPath(string packageName) private readonly static Dictionary<string, string> _cachedBundleFileFolder = new Dictionary<string, string>(100);
public static string GetCachedBundleFileFolderPath(string packageName)
{ {
string root = PathHelper.MakePersistentLoadPath(CacheFolderName); if (_cachedBundleFileFolder.TryGetValue(packageName, out string value) == false)
return $"{root}/{packageName}"; {
string root = PathHelper.MakePersistentLoadPath(CacheFolderName);
value = $"{root}/{packageName}/{CachedBundleFileFolder}";
_cachedBundleFileFolder.Add(packageName, value);
}
return value;
}
/// <summary>
/// 获取缓存的RawFile文件夹路径
/// </summary>
private readonly static Dictionary<string, string> _cachedRawFileFolder = new Dictionary<string, string>(100);
public static string GetCachedRawFileFolderPath(string packageName)
{
if (_cachedRawFileFolder.TryGetValue(packageName, out string value) == false)
{
string root = PathHelper.MakePersistentLoadPath(CacheFolderName);
value = $"{root}/{packageName}/{CachedRawFileFolder}";
_cachedRawFileFolder.Add(packageName, value);
}
return value;
} }
/// <summary> /// <summary>

View File

@@ -2,15 +2,35 @@
namespace YooAsset namespace YooAsset
{ {
/// <summary>
/// 自定义日志处理
/// </summary>
public interface ILogger
{
void Log(string message);
void Warning(string message);
void Error(string message);
void Exception(System.Exception exception);
}
internal static class YooLogger internal static class YooLogger
{ {
public static ILogger Logger = null;
/// <summary> /// <summary>
/// 日志 /// 日志
/// </summary> /// </summary>
[Conditional("DEBUG")] [Conditional("DEBUG")]
public static void Log(string info) public static void Log(string info)
{ {
UnityEngine.Debug.Log(info); if (Logger != null)
{
Logger.Log(info);
}
else
{
UnityEngine.Debug.Log(info);
}
} }
/// <summary> /// <summary>
@@ -18,7 +38,14 @@ namespace YooAsset
/// </summary> /// </summary>
public static void Warning(string info) public static void Warning(string info)
{ {
UnityEngine.Debug.LogWarning(info); if (Logger != null)
{
Logger.Warning(info);
}
else
{
UnityEngine.Debug.LogWarning(info);
}
} }
/// <summary> /// <summary>
@@ -26,7 +53,14 @@ namespace YooAsset
/// </summary> /// </summary>
public static void Error(string info) public static void Error(string info)
{ {
UnityEngine.Debug.LogError(info); if (Logger != null)
{
Logger.Error(info);
}
else
{
UnityEngine.Debug.LogError(info);
}
} }
/// <summary> /// <summary>
@@ -34,7 +68,14 @@ namespace YooAsset
/// </summary> /// </summary>
public static void Exception(System.Exception exception) public static void Exception(System.Exception exception)
{ {
UnityEngine.Debug.LogException(exception); if (Logger != null)
{
Logger.Exception(exception);
}
else
{
UnityEngine.Debug.LogException(exception);
}
} }
} }
} }

View File

@@ -15,13 +15,16 @@ namespace YooAsset
/// <summary> /// <summary>
/// 初始化资源系统 /// 初始化资源系统
/// </summary> /// </summary>
public static void Initialize() /// <param name="logger">自定义日志处理</param>
public static void Initialize(ILogger logger = null)
{ {
if (_isInitialize) if (_isInitialize)
throw new Exception($"{nameof(YooAssets)} is initialized !"); throw new Exception($"{nameof(YooAssets)} is initialized !");
if (_isInitialize == false) if (_isInitialize == false)
{ {
YooLogger.Logger = logger;
// 创建驱动器 // 创建驱动器
_isInitialize = true; _isInitialize = true;
_driver = new UnityEngine.GameObject($"[{nameof(YooAssets)}]"); _driver = new UnityEngine.GameObject($"[{nameof(YooAssets)}]");
@@ -34,8 +37,8 @@ namespace YooAsset
_driver.AddComponent<RemoteDebuggerInRuntime>(); _driver.AddComponent<RemoteDebuggerInRuntime>();
#endif #endif
// 初始化异步系统
OperationSystem.Initialize(); OperationSystem.Initialize();
DownloadSystem.Initialize();
} }
} }
@@ -184,6 +187,14 @@ namespace YooAsset
DownloadSystem.CertificateHandlerInstance = instance; DownloadSystem.CertificateHandlerInstance = instance;
} }
/// <summary>
/// 设置下载系统参数,自定义下载请求
/// </summary>
public static void SetDownloadSystemUnityWebRequest(DownloadRequestDelegate requestDelegate)
{
DownloadSystem.RequestDelegate = requestDelegate;
}
/// <summary> /// <summary>
/// 设置异步系统参数,每帧执行消耗的最大时间切片(单位:毫秒) /// 设置异步系统参数,每帧执行消耗的最大时间切片(单位:毫秒)
/// </summary> /// </summary>

View File

@@ -16,7 +16,7 @@ MonoBehaviour:
BuildMode: 0 BuildMode: 0
BuildPackage: DefaultPackage BuildPackage: DefaultPackage
CompressOption: 2 CompressOption: 2
OutputNameStyle: 4 OutputNameStyle: 1
CopyBuildinFileOption: 1 CopyBuildinFileOption: 1
CopyBuildinFileTags: CopyBuildinFileTags:
EncyptionClassName: FileStreamEncryption EncyptionClassName: FileStreamEncryption

View File

@@ -2,21 +2,24 @@
<root Version="2.3"> <root Version="2.3">
<Common AutoAddressable="True" UniqueBundleName="False" ShowPackageView="False" ShowEditorAlias="False" /> <Common AutoAddressable="True" UniqueBundleName="False" ShowPackageView="False" ShowEditorAlias="False" />
<Package PackageName="DefaultPackage" PackageDesc=""> <Package PackageName="DefaultPackage" PackageDesc="">
<Group GroupName="battle" GroupDesc="" AssetTags=""> <Group GroupName="battle" GroupDesc="战斗" AssetTags="">
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/Effect" CollectGUID="80d76514758554baaa96a9efffe9f3ef" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackDirectory" FilterRule="CollectAll" UserData="" AssetTags="" /> <Collector CollectPath="Assets/Samples/Space Shooter/GameRes/Effect" CollectGUID="80d76514758554baaa96a9efffe9f3ef" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackDirectory" FilterRule="CollectAll" UserData="" AssetTags="" />
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/Entity" CollectGUID="4d7c84745db8e884f8020a8c5356e67c" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackDirectory" FilterRule="CollectAll" UserData="" AssetTags="" /> <Collector CollectPath="Assets/Samples/Space Shooter/GameRes/Entity" CollectGUID="4d7c84745db8e884f8020a8c5356e67c" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackDirectory" FilterRule="CollectAll" UserData="" AssetTags="" />
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/Audio" CollectGUID="306075fbe00b24251b6c889984a7a7d5" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackDirectory" FilterRule="CollectAll" UserData="" AssetTags="" /> <Collector CollectPath="Assets/Samples/Space Shooter/GameRes/Audio" CollectGUID="306075fbe00b24251b6c889984a7a7d5" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackDirectory" FilterRule="CollectAll" UserData="" AssetTags="" />
</Group> </Group>
<Group GroupName="shader" GroupDesc="" AssetTags=""> <Group GroupName="shader" GroupDesc="着色器" AssetTags="">
<Collector CollectPath="Assets/Samples/Space Shooter/GameArt/ShaderVariants" CollectGUID="00781758c26692e40a9634ddeac838be" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackShaderVariants" FilterRule="CollectShaderVariants" UserData="" AssetTags="" /> <Collector CollectPath="Assets/Samples/Space Shooter/GameArt/ShaderVariants" CollectGUID="00781758c26692e40a9634ddeac838be" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackShaderVariants" FilterRule="CollectShaderVariants" UserData="" AssetTags="" />
</Group> </Group>
<Group GroupName="scene" GroupDesc="" AssetTags=""> <Group GroupName="scene" GroupDesc="场景" AssetTags="">
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/Scene" CollectGUID="6070eae1192f2994887f2983a177d503" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackSeparately" FilterRule="CollectAll" UserData="" AssetTags="" /> <Collector CollectPath="Assets/Samples/Space Shooter/GameRes/Scene" CollectGUID="6070eae1192f2994887f2983a177d503" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackSeparately" FilterRule="CollectAll" UserData="" AssetTags="" />
</Group> </Group>
<Group GroupName="ugui" GroupDesc="" AssetTags=""> <Group GroupName="ugui" GroupDesc="面板" AssetTags="">
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/UIImage" CollectGUID="30c57db62bb02a24590e7046d3a9e33a" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackDirectory" FilterRule="CollectAll" UserData="" AssetTags="" /> <Collector CollectPath="Assets/Samples/Space Shooter/GameRes/UIImage" CollectGUID="30c57db62bb02a24590e7046d3a9e33a" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackDirectory" FilterRule="CollectAll" UserData="" AssetTags="" />
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/UIPanel" CollectGUID="12d33f33f3a55224c9c747d7bffa1c68" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackSeparately" FilterRule="CollectAll" UserData="" AssetTags="" /> <Collector CollectPath="Assets/Samples/Space Shooter/GameRes/UIPanel" CollectGUID="12d33f33f3a55224c9c747d7bffa1c68" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackSeparately" FilterRule="CollectAll" UserData="" AssetTags="" />
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/UISprite" CollectGUID="01865ad6f7c806147b6cb37f2d83bc96" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackTopDirectory" FilterRule="CollectAll" UserData="" AssetTags="" /> <Collector CollectPath="Assets/Samples/Space Shooter/GameRes/UISprite" CollectGUID="01865ad6f7c806147b6cb37f2d83bc96" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackTopDirectory" FilterRule="CollectAll" UserData="" AssetTags="" />
</Group> </Group>
<Group GroupName="config" GroupDesc="配置表" AssetTags="">
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/Config" CollectGUID="1894d23646ddbf8479e579cc03261dde" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackRawFile" FilterRule="CollectAll" UserData="" AssetTags="" />
</Group>
</Package> </Package>
</root> </root>

View File

@@ -21,7 +21,7 @@ MonoBehaviour:
PackageDesc: PackageDesc:
Groups: Groups:
- GroupName: battle - GroupName: battle
GroupDesc: GroupDesc: "\u6218\u6597"
AssetTags: AssetTags:
ActiveRuleName: EnableGroup ActiveRuleName: EnableGroup
Collectors: Collectors:
@@ -50,7 +50,7 @@ MonoBehaviour:
AssetTags: AssetTags:
UserData: UserData:
- GroupName: shader - GroupName: shader
GroupDesc: GroupDesc: "\u7740\u8272\u5668"
AssetTags: AssetTags:
ActiveRuleName: EnableGroup ActiveRuleName: EnableGroup
Collectors: Collectors:
@@ -63,7 +63,7 @@ MonoBehaviour:
AssetTags: AssetTags:
UserData: UserData:
- GroupName: scene - GroupName: scene
GroupDesc: GroupDesc: "\u573A\u666F"
AssetTags: AssetTags:
ActiveRuleName: EnableGroup ActiveRuleName: EnableGroup
Collectors: Collectors:
@@ -76,7 +76,7 @@ MonoBehaviour:
AssetTags: AssetTags:
UserData: UserData:
- GroupName: ugui - GroupName: ugui
GroupDesc: GroupDesc: "\u9762\u677F"
AssetTags: AssetTags:
ActiveRuleName: EnableGroup ActiveRuleName: EnableGroup
Collectors: Collectors:
@@ -104,3 +104,16 @@ MonoBehaviour:
FilterRuleName: CollectAll FilterRuleName: CollectAll
AssetTags: AssetTags:
UserData: UserData:
- GroupName: config
GroupDesc: "\u914D\u7F6E\u8868"
AssetTags:
ActiveRuleName: EnableGroup
Collectors:
- CollectPath: Assets/Samples/Space Shooter/GameRes/Config
CollectorGUID: 1894d23646ddbf8479e579cc03261dde
CollectorType: 0
AddressRuleName: AddressByFileName
PackRuleName: PackRawFile
FilterRuleName: CollectAll
AssetTags:
UserData:

View File

@@ -12,4 +12,6 @@ MonoBehaviour:
m_Script: {fileID: 11500000, guid: 44454e58a49818040a1aef5799e71b30, type: 3} m_Script: {fileID: 11500000, guid: 44454e58a49818040a1aef5799e71b30, type: 3}
m_Name: ShaderVariantCollectorSetting m_Name: ShaderVariantCollectorSetting
m_EditorClassIdentifier: m_EditorClassIdentifier:
SavePath: Assets/Samples/BassicSample/GameArt/ShaderVariants/MyShaderVariants.shadervariants SavePath: Assets/ShaderVariants/MyShaderVariants.shadervariants
CollectPackage: DefaultPackage
ProcessCapacity: 1000

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1894d23646ddbf8479e579cc03261dde
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1 @@
Powered by YooAsset @tuyoogame

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 66ce1e032fc66694bb3fce32961d78d5
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -14,7 +14,7 @@ GameObject:
- component: {fileID: 8153114547710269446} - component: {fileID: 8153114547710269446}
m_Layer: 0 m_Layer: 0
m_Name: asteroid01 m_Name: asteroid01
m_TagString: Asteroid m_TagString: Untagged
m_Icon: {fileID: 0} m_Icon: {fileID: 0}
m_NavMeshLayer: 0 m_NavMeshLayer: 0
m_StaticEditorFlags: 0 m_StaticEditorFlags: 0

View File

@@ -93,7 +93,7 @@ GameObject:
- component: {fileID: 6609967452740485438} - component: {fileID: 6609967452740485438}
m_Layer: 0 m_Layer: 0
m_Name: asteroid02 m_Name: asteroid02
m_TagString: Asteroid m_TagString: Untagged
m_Icon: {fileID: 0} m_Icon: {fileID: 0}
m_NavMeshLayer: 0 m_NavMeshLayer: 0
m_StaticEditorFlags: 0 m_StaticEditorFlags: 0

View File

@@ -93,7 +93,7 @@ GameObject:
- component: {fileID: 4093119317317235419} - component: {fileID: 4093119317317235419}
m_Layer: 0 m_Layer: 0
m_Name: asteroid03 m_Name: asteroid03
m_TagString: Asteroid m_TagString: Untagged
m_Icon: {fileID: 0} m_Icon: {fileID: 0}
m_NavMeshLayer: 0 m_NavMeshLayer: 0
m_StaticEditorFlags: 0 m_StaticEditorFlags: 0

View File

@@ -14,7 +14,7 @@ GameObject:
- component: {fileID: 7168776728617073029} - component: {fileID: 7168776728617073029}
m_Layer: 0 m_Layer: 0
m_Name: enemy_bullet m_Name: enemy_bullet
m_TagString: EnemyBullet m_TagString: Untagged
m_Icon: {fileID: 0} m_Icon: {fileID: 0}
m_NavMeshLayer: 0 m_NavMeshLayer: 0
m_StaticEditorFlags: 0 m_StaticEditorFlags: 0

View File

@@ -4714,7 +4714,7 @@ GameObject:
- component: {fileID: 8046716069608073559} - component: {fileID: 8046716069608073559}
m_Layer: 0 m_Layer: 0
m_Name: enemy_ship m_Name: enemy_ship
m_TagString: Enemy m_TagString: Untagged
m_Icon: {fileID: 0} m_Icon: {fileID: 0}
m_NavMeshLayer: 0 m_NavMeshLayer: 0
m_StaticEditorFlags: 0 m_StaticEditorFlags: 0

View File

@@ -14,7 +14,7 @@ GameObject:
- component: {fileID: 2296800368016434796} - component: {fileID: 2296800368016434796}
m_Layer: 0 m_Layer: 0
m_Name: player_bullet m_Name: player_bullet
m_TagString: PlayerBullet m_TagString: Untagged
m_Icon: {fileID: 0} m_Icon: {fileID: 0}
m_NavMeshLayer: 0 m_NavMeshLayer: 0
m_StaticEditorFlags: 0 m_StaticEditorFlags: 0

View File

@@ -9481,7 +9481,7 @@ GameObject:
- component: {fileID: 5342208951388308754} - component: {fileID: 5342208951388308754}
m_Layer: 0 m_Layer: 0
m_Name: player_ship m_Name: player_ship
m_TagString: Player m_TagString: Untagged
m_Icon: {fileID: 0} m_Icon: {fileID: 0}
m_NavMeshLayer: 0 m_NavMeshLayer: 0
m_StaticEditorFlags: 0 m_StaticEditorFlags: 0

View File

@@ -129,7 +129,7 @@ GameObject:
- component: {fileID: 37} - component: {fileID: 37}
m_Layer: 0 m_Layer: 0
m_Name: Boundary m_Name: Boundary
m_TagString: Boundary m_TagString: Untagged
m_Icon: {fileID: 0} m_Icon: {fileID: 0}
m_NavMeshLayer: 0 m_NavMeshLayer: 0
m_StaticEditorFlags: 0 m_StaticEditorFlags: 0
@@ -10999,7 +10999,7 @@ GameObject:
- component: {fileID: 1691764579} - component: {fileID: 1691764579}
m_Layer: 0 m_Layer: 0
m_Name: BoundaryWorld m_Name: BoundaryWorld
m_TagString: Boundary m_TagString: Untagged
m_Icon: {fileID: 0} m_Icon: {fileID: 0}
m_NavMeshLayer: 0 m_NavMeshLayer: 0
m_StaticEditorFlags: 0 m_StaticEditorFlags: 0

View File

@@ -66,7 +66,7 @@ MonoBehaviour:
m_Calls: [] m_Calls: []
m_FontData: m_FontData:
m_Font: {fileID: 12800000, guid: 8297a2bf97dbbba468bd2518d003a876, type: 3} m_Font: {fileID: 12800000, guid: 8297a2bf97dbbba468bd2518d003a876, type: 3}
m_FontSize: 28 m_FontSize: 22
m_FontStyle: 0 m_FontStyle: 0
m_BestFit: 0 m_BestFit: 0
m_MinSize: 2 m_MinSize: 2
@@ -77,7 +77,7 @@ MonoBehaviour:
m_HorizontalOverflow: 0 m_HorizontalOverflow: 0
m_VerticalOverflow: 0 m_VerticalOverflow: 0
m_LineSpacing: 1 m_LineSpacing: 1
m_Text: Powered by YooAsset m_Text:
--- !u!1 &4142826567245113227 --- !u!1 &4142826567245113227
GameObject: GameObject:
m_ObjectHideFlags: 0 m_ObjectHideFlags: 0

View File

@@ -3,21 +3,11 @@ using System.IO;
using System.Text; using System.Text;
using YooAsset; using YooAsset;
public class EncryptionNone : IEncryptionServices
{
public EncryptResult Encrypt(EncryptFileInfo fileInfo)
{
EncryptResult result = new EncryptResult();
result.LoadMethod = EBundleLoadMethod.Normal;
return result;
}
}
public class FileOffsetEncryption : IEncryptionServices public class FileOffsetEncryption : IEncryptionServices
{ {
public EncryptResult Encrypt(EncryptFileInfo fileInfo) public EncryptResult Encrypt(EncryptFileInfo fileInfo)
{ {
if(fileInfo.BundleName.Contains("gameres_music")) if (fileInfo.BundleName.Contains("_gameres_audio"))
{ {
int offset = 32; int offset = 32;
byte[] fileData = File.ReadAllBytes(fileInfo.FilePath); byte[] fileData = File.ReadAllBytes(fileInfo.FilePath);

View File

@@ -25,7 +25,8 @@ public class EntityAsteroid : MonoBehaviour
} }
void OnTriggerEnter(Collider other) void OnTriggerEnter(Collider other)
{ {
if (other.CompareTag("PlayerBullet")) var name = other.gameObject.name;
if (name.StartsWith("player"))
{ {
BattleEventDefine.AsteroidExplosion.SendEventMessage(this.transform.position, this.transform.rotation); BattleEventDefine.AsteroidExplosion.SendEventMessage(this.transform.position, this.transform.rotation);
_handle.Restore(); _handle.Restore();
@@ -34,7 +35,8 @@ public class EntityAsteroid : MonoBehaviour
} }
void OnTriggerExit(Collider other) void OnTriggerExit(Collider other)
{ {
if (other.CompareTag("Boundary")) var name = other.gameObject.name;
if (name.StartsWith("Boundary"))
{ {
_handle.Restore(); _handle.Restore();
_handle = null; _handle = null;

View File

@@ -19,25 +19,27 @@ public class EntityBullet : MonoBehaviour
void Awake() void Awake()
{ {
_rigidbody = this.transform.GetComponent<Rigidbody>(); _rigidbody = this.transform.GetComponent<Rigidbody>();
} }
void OnTriggerEnter(Collider other) void OnTriggerEnter(Collider other)
{ {
if (other.CompareTag("Boundary")) var name = other.gameObject.name;
if (name.StartsWith("Boundary"))
return; return;
if (this.gameObject.CompareTag("EnemyBullet")) var goName = this.gameObject.name;
if (goName.StartsWith("enemy_bullet"))
{ {
if (other.CompareTag("Enemy") == false) if (name.StartsWith("enemy") == false)
{ {
_handle.Restore(); _handle.Restore();
_handle = null; _handle = null;
} }
} }
if (this.gameObject.CompareTag("PlayerBullet")) if (goName.StartsWith("player_bullet"))
{ {
if (other.CompareTag("Player") == false) if (name.StartsWith("player") == false)
{ {
_handle.Restore(); _handle.Restore();
_handle = null; _handle = null;
@@ -46,7 +48,8 @@ public class EntityBullet : MonoBehaviour
} }
void OnTriggerExit(Collider other) void OnTriggerExit(Collider other)
{ {
if (other.CompareTag("Boundary")) var name = other.gameObject.name;
if (name.StartsWith("Boundary"))
{ {
_handle.Restore(); _handle.Restore();
_handle = null; _handle = null;

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