update yooasset2.0

This commit is contained in:
hevinci
2023-09-20 16:09:52 +08:00
parent 880b6d429d
commit 01cf9ccd54
369 changed files with 6557 additions and 5490 deletions
@@ -1,29 +0,0 @@
namespace YooAsset
{
/// <summary>
/// Bundle文件的加载方法
/// </summary>
public enum EBundleLoadMethod
{
/// <summary>
/// 正常加载(不需要解密)
/// </summary>
Normal = 0,
/// <summary>
/// 通过文件偏移来解密加载
/// </summary>
LoadFromFileOffset = 1,
/// <summary>
/// 通过文件内存来解密加载
/// </summary>
LoadFromMemory = 2,
/// <summary>
/// 通过文件流来解密加载
/// </summary>
LoadFromStream = 3,
}
}
@@ -0,0 +1,103 @@
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace YooAsset
{
internal static class CacheHelper
{
/// <summary>
/// 禁用Unity缓存系统在WebGL平台
/// </summary>
public static bool DisableUnityCacheOnWebGL = false;
/// <summary>
/// 验证缓存文件(子线程内操作)
/// </summary>
public static EVerifyResult VerifyingCacheFile(VerifyCacheFileElement element, EVerifyLevel verifyLevel)
{
try
{
if (verifyLevel == EVerifyLevel.Low)
{
if (File.Exists(element.InfoFilePath) == false)
return EVerifyResult.InfoFileNotExisted;
if (File.Exists(element.DataFilePath) == false)
return EVerifyResult.DataFileNotExisted;
return EVerifyResult.Succeed;
}
else
{
if (File.Exists(element.InfoFilePath) == false)
return EVerifyResult.InfoFileNotExisted;
// 解析信息文件获取验证数据
CacheFileInfo.ReadInfoFromFile(element.InfoFilePath, out element.DataFileCRC, out element.DataFileSize);
}
}
catch (Exception)
{
return EVerifyResult.Exception;
}
return VerifyingInternal(element.DataFilePath, element.DataFileSize, element.DataFileCRC, verifyLevel);
}
/// <summary>
/// 验证下载文件(子线程内操作)
/// </summary>
public static EVerifyResult VerifyingTempFile(VerifyTempFileElement element)
{
return VerifyingInternal(element.TempDataFilePath, element.FileSize, element.FileCRC, EVerifyLevel.High);
}
/// <summary>
/// 验证记录文件(主线程内操作)
/// </summary>
public static EVerifyResult VerifyingRecordFile(CacheManager cache, string cacheGUID)
{
var wrapper = cache.TryGetWrapper(cacheGUID);
if (wrapper == null)
return EVerifyResult.CacheNotFound;
EVerifyResult result = VerifyingInternal(wrapper.DataFilePath, wrapper.DataFileSize, wrapper.DataFileCRC, EVerifyLevel.High);
return result;
}
private static EVerifyResult VerifyingInternal(string filePath, long fileSize, string fileCRC, EVerifyLevel verifyLevel)
{
try
{
if (File.Exists(filePath) == false)
return EVerifyResult.DataFileNotExisted;
// 先验证文件大小
long size = FileUtility.GetFileSize(filePath);
if (size < fileSize)
return EVerifyResult.FileNotComplete;
else if (size > fileSize)
return EVerifyResult.FileOverflow;
// 再验证文件CRC
if (verifyLevel == EVerifyLevel.High)
{
string crc = HashUtility.FileCRC32(filePath);
if (crc == fileCRC)
return EVerifyResult.Succeed;
else
return EVerifyResult.FileCrcError;
}
else
{
return EVerifyResult.Succeed;
}
}
catch (Exception)
{
return EVerifyResult.Exception;
}
}
}
}
@@ -5,7 +5,7 @@ using System.Collections.Generic;
namespace YooAsset
{
internal class PackageCache
internal class CacheManager
{
internal class RecordWrapper
{
@@ -26,14 +26,20 @@ namespace YooAsset
private readonly Dictionary<string, RecordWrapper> _wrappers = new Dictionary<string, RecordWrapper>();
/// <summary>
/// 包裹名称
/// 所属包裹
/// </summary>
public string PackageName { private set; get; }
public readonly string PackageName;
/// <summary>
/// 验证级别
/// </summary>
public readonly EVerifyLevel BootVerifyLevel;
public PackageCache(string packageName)
public CacheManager(string packageName, EVerifyLevel bootVerifyLevel)
{
PackageName = packageName;
BootVerifyLevel = bootVerifyLevel;
}
/// <summary>
@@ -44,14 +50,6 @@ namespace YooAsset
_wrappers.Clear();
}
/// <summary>
/// 获取缓存文件总数
/// </summary>
public int GetCachedFilesCount()
{
return _wrappers.Count;
}
/// <summary>
/// 查询缓存记录
/// </summary>
@@ -76,10 +74,26 @@ namespace YooAsset
}
/// <summary>
/// 丢弃验证结果
/// 丢弃验证结果并删除缓存文件
/// </summary>
public void Discard(string cacheGUID)
{
var wrapper = TryGetWrapper(cacheGUID);
if (wrapper != null)
{
try
{
string dataFilePath = wrapper.DataFilePath;
FileInfo fileInfo = new FileInfo(dataFilePath);
if (fileInfo.Exists)
fileInfo.Directory.Delete(true);
}
catch (Exception e)
{
YooLogger.Error($"Failed to delete cache file ! {e.Message}");
}
}
if (_wrappers.ContainsKey(cacheGUID))
{
_wrappers.Remove(cacheGUID);
@@ -97,7 +111,18 @@ namespace YooAsset
return null;
}
internal List<string> GetAllKeys()
/// <summary>
/// 获取缓存文件总数
/// </summary>
public int GetAllCachedFilesCount()
{
return _wrappers.Count;
}
/// <summary>
/// 获取缓存GUID集合
/// </summary>
public List<string> GetAllCachedGUIDs()
{
List<string> keys = new List<string>(_wrappers.Keys.Count);
var keyCollection = _wrappers.Keys;
@@ -1,217 +0,0 @@
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace YooAsset
{
internal static class CacheSystem
{
private readonly static Dictionary<string, PackageCache> _cachedDic = new Dictionary<string, PackageCache>(1000);
/// <summary>
/// 禁用Unity缓存系统在WebGL平台
/// </summary>
public static bool DisableUnityCacheOnWebGL = false;
/// <summary>
/// 初始化时的验证级别
/// </summary>
public static EVerifyLevel InitVerifyLevel { set; get; } = EVerifyLevel.Middle;
/// <summary>
/// 清空所有数据
/// </summary>
public static void ClearAll()
{
_cachedDic.Clear();
}
/// <summary>
/// 清空指定包裹的所有缓存数据
/// </summary>
public static void ClearPackage(string packageName)
{
var cache = GetOrCreateCache(packageName);
cache.ClearAll();
}
/// <summary>
/// 获取缓存文件总数
/// </summary>
public static int GetCachedFilesCount(string packageName)
{
var cache = GetOrCreateCache(packageName);
return cache.GetCachedFilesCount();
}
/// <summary>
/// 查询是否为验证文件
/// </summary>
public static bool IsCached(string packageName, string cacheGUID)
{
var cache = GetOrCreateCache(packageName);
return cache.IsCached(cacheGUID);
}
/// <summary>
/// 录入验证的文件
/// </summary>
public static void RecordFile(string packageName, string cacheGUID, PackageCache.RecordWrapper wrapper)
{
//YooLogger.Log($"Record file : {packageName} = {cacheGUID}");
var cache = GetOrCreateCache(packageName);
cache.Record(cacheGUID, wrapper);
}
/// <summary>
/// 丢弃验证的文件(同时删除文件)
/// </summary>
public static void DiscardFile(string packageName, string cacheGUID)
{
var cache = GetOrCreateCache(packageName);
var wrapper = cache.TryGetWrapper(cacheGUID);
if (wrapper == null)
return;
cache.Discard(cacheGUID);
try
{
string dataFilePath = wrapper.DataFilePath;
FileInfo fileInfo = new FileInfo(dataFilePath);
if (fileInfo.Exists)
fileInfo.Directory.Delete(true);
}
catch (Exception e)
{
YooLogger.Error($"Failed to delete cache file ! {e.Message}");
}
}
/// <summary>
/// 验证缓存文件(子线程内操作)
/// </summary>
public static EVerifyResult VerifyingCacheFile(VerifyCacheFileElement element)
{
try
{
if (InitVerifyLevel == EVerifyLevel.Low)
{
if (File.Exists(element.InfoFilePath) == false)
return EVerifyResult.InfoFileNotExisted;
if (File.Exists(element.DataFilePath) == false)
return EVerifyResult.DataFileNotExisted;
return EVerifyResult.Succeed;
}
else
{
if (File.Exists(element.InfoFilePath) == false)
return EVerifyResult.InfoFileNotExisted;
// 解析信息文件获取验证数据
CacheFileInfo.ReadInfoFromFile(element.InfoFilePath, out element.DataFileCRC, out element.DataFileSize);
}
}
catch (Exception)
{
return EVerifyResult.Exception;
}
return VerifyingInternal(element.DataFilePath, element.DataFileSize, element.DataFileCRC, InitVerifyLevel);
}
/// <summary>
/// 验证下载文件(子线程内操作)
/// </summary>
public static EVerifyResult VerifyingTempFile(VerifyTempFileElement element)
{
return VerifyingInternal(element.TempDataFilePath, element.FileSize, element.FileCRC, EVerifyLevel.High);
}
/// <summary>
/// 验证记录文件(主线程内操作)
/// </summary>
public static EVerifyResult VerifyingRecordFile(string packageName, string cacheGUID)
{
var cache = GetOrCreateCache(packageName);
var wrapper = cache.TryGetWrapper(cacheGUID);
if (wrapper == null)
return EVerifyResult.CacheNotFound;
EVerifyResult result = VerifyingInternal(wrapper.DataFilePath, wrapper.DataFileSize, wrapper.DataFileCRC, EVerifyLevel.High);
return result;
}
/// <summary>
/// 获取未被使用的缓存文件
/// </summary>
public static List<string> GetUnusedCacheGUIDs(ResourcePackage package)
{
var cache = GetOrCreateCache(package.PackageName);
var keys = cache.GetAllKeys();
List<string> result = new List<string>(keys.Count);
foreach (var cacheGUID in keys)
{
if (package.IsIncludeBundleFile(cacheGUID) == false)
{
result.Add(cacheGUID);
}
}
return result;
}
/// <summary>
/// 获取所有的缓存文件
/// </summary>
public static List<string> GetAllCacheGUIDs(ResourcePackage package)
{
var cache = GetOrCreateCache(package.PackageName);
return cache.GetAllKeys();
}
private static EVerifyResult VerifyingInternal(string filePath, long fileSize, string fileCRC, EVerifyLevel verifyLevel)
{
try
{
if (File.Exists(filePath) == false)
return EVerifyResult.DataFileNotExisted;
// 先验证文件大小
long size = FileUtility.GetFileSize(filePath);
if (size < fileSize)
return EVerifyResult.FileNotComplete;
else if (size > fileSize)
return EVerifyResult.FileOverflow;
// 再验证文件CRC
if (verifyLevel == EVerifyLevel.High)
{
string crc = HashUtility.FileCRC32(filePath);
if (crc == fileCRC)
return EVerifyResult.Succeed;
else
return EVerifyResult.FileCrcError;
}
else
{
return EVerifyResult.Succeed;
}
}
catch (Exception)
{
return EVerifyResult.Exception;
}
}
private static PackageCache GetOrCreateCache(string packageName)
{
if (_cachedDic.TryGetValue(packageName, out PackageCache cache) == false)
{
cache = new PackageCache(packageName);
_cachedDic.Add(packageName, cache);
}
return cache;
}
}
}
@@ -17,14 +17,14 @@ namespace YooAsset
Done,
}
private readonly ResourcePackage _package;
private readonly CacheManager _cache;
private List<string> _allCacheGUIDs;
private int _fileTotalCount = 0;
private ESteps _steps = ESteps.None;
internal ClearAllCacheFilesOperation(ResourcePackage package)
internal ClearAllCacheFilesOperation(CacheManager cache)
{
_package = package;
_cache = cache;
}
internal override void Start()
{
@@ -37,7 +37,7 @@ namespace YooAsset
if (_steps == ESteps.GetAllCacheFiles)
{
_allCacheGUIDs = CacheSystem.GetAllCacheGUIDs(_package);
_allCacheGUIDs = _cache.GetAllCachedGUIDs();
_fileTotalCount = _allCacheGUIDs.Count;
YooLogger.Log($"Found all cache file count : {_fileTotalCount}");
_steps = ESteps.ClearAllCacheFiles;
@@ -48,7 +48,7 @@ namespace YooAsset
for (int i = _allCacheGUIDs.Count - 1; i >= 0; i--)
{
string cacheGUID = _allCacheGUIDs[i];
CacheSystem.DiscardFile(_package.PackageName, cacheGUID);
_cache.Discard(cacheGUID);
_allCacheGUIDs.RemoveAt(i);
if (OperationSystem.IsBusy)
@@ -18,13 +18,15 @@ namespace YooAsset
}
private readonly ResourcePackage _package;
private readonly CacheManager _cache;
private List<string> _unusedCacheGUIDs;
private int _unusedFileTotalCount = 0;
private ESteps _steps = ESteps.None;
internal ClearUnusedCacheFilesOperation(ResourcePackage package)
internal ClearUnusedCacheFilesOperation(ResourcePackage package, CacheManager cache)
{
_package = package;
_cache = cache;
}
internal override void Start()
{
@@ -37,7 +39,7 @@ namespace YooAsset
if (_steps == ESteps.GetUnusedCacheFiles)
{
_unusedCacheGUIDs = CacheSystem.GetUnusedCacheGUIDs(_package);
_unusedCacheGUIDs = GetUnusedCacheGUIDs();
_unusedFileTotalCount = _unusedCacheGUIDs.Count;
YooLogger.Log($"Found unused cache file count : {_unusedFileTotalCount}");
_steps = ESteps.ClearUnusedCacheFiles;
@@ -48,7 +50,7 @@ namespace YooAsset
for (int i = _unusedCacheGUIDs.Count - 1; i >= 0; i--)
{
string cacheGUID = _unusedCacheGUIDs[i];
CacheSystem.DiscardFile(_package.PackageName, cacheGUID);
_cache.Discard(cacheGUID);
_unusedCacheGUIDs.RemoveAt(i);
if (OperationSystem.IsBusy)
@@ -67,5 +69,19 @@ namespace YooAsset
}
}
}
private List<string> GetUnusedCacheGUIDs()
{
var allCacheGUIDs = _cache.GetAllCachedGUIDs();
List<string> result = new List<string>(allCacheGUIDs.Count);
foreach (var cacheGUID in allCacheGUIDs)
{
if (_package.IsIncludeBundleFile(cacheGUID) == false)
{
result.Add(cacheGUID);
}
}
return result;
}
}
}
@@ -0,0 +1,126 @@
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset
{
internal sealed class FindCacheFilesOperation : AsyncOperationBase
{
private enum ESteps
{
None,
Prepare,
UpdateCacheFiles,
Done,
}
private readonly PersistentManager _persistent;
private readonly CacheManager _cache;
private IEnumerator<DirectoryInfo> _filesEnumerator = null;
private float _verifyStartTime;
private ESteps _steps = ESteps.None;
/// <summary>
/// 需要验证的元素
/// </summary>
public readonly List<VerifyCacheFileElement> VerifyElements = new List<VerifyCacheFileElement>(5000);
public FindCacheFilesOperation(PersistentManager persistent, CacheManager cache)
{
_persistent = persistent;
_cache = cache;
}
internal override void Start()
{
_steps = ESteps.Prepare;
_verifyStartTime = UnityEngine.Time.realtimeSinceStartup;
}
internal override void Update()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.Prepare)
{
string rootPath = _persistent.SandboxCacheFilesRoot;
DirectoryInfo rootDirectory = new DirectoryInfo(rootPath);
if (rootDirectory.Exists)
{
var directorieInfos = rootDirectory.EnumerateDirectories();
_filesEnumerator = directorieInfos.GetEnumerator();
}
_steps = ESteps.UpdateCacheFiles;
}
if (_steps == ESteps.UpdateCacheFiles)
{
if (UpdateCacheFiles())
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 UpdateCacheFiles()
{
if (_filesEnumerator == null)
return false;
bool isFindItem;
while (true)
{
isFindItem = _filesEnumerator.MoveNext();
if (isFindItem == false)
break;
var rootFoder = _filesEnumerator.Current;
var childDirectories = rootFoder.GetDirectories();
foreach (var chidDirectory in childDirectories)
{
string cacheGUID = chidDirectory.Name;
if (_cache.IsCached(cacheGUID))
continue;
// 创建验证元素类
string fileRootPath = chidDirectory.FullName;
string dataFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleDataFileName}";
string infoFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleInfoFileName}";
if (_persistent.AppendFileExtension)
{
string fileExtension = FindFileExtension(chidDirectory);
if (string.IsNullOrEmpty(fileExtension) == false)
dataFilePath += fileExtension;
}
VerifyCacheFileElement element = new VerifyCacheFileElement(_cache.PackageName, cacheGUID, fileRootPath, dataFilePath, infoFilePath);
VerifyElements.Add(element);
}
if (OperationSystem.IsBusy)
break;
}
return isFindItem;
}
private string FindFileExtension(DirectoryInfo directoryInfo)
{
string dataFileExtension = string.Empty;
var fileInfos = directoryInfo.GetFiles();
foreach (var fileInfo in fileInfos)
{
if (fileInfo.Extension == ".temp")
continue;
if (fileInfo.Name.StartsWith(YooAssetSettings.CacheBundleDataFileName))
{
dataFileExtension = fileInfo.Extension;
break;
}
}
return dataFileExtension;
}
}
}
@@ -8,12 +8,12 @@ namespace YooAsset
{
internal abstract class VerifyCacheFilesOperation : AsyncOperationBase
{
public static VerifyCacheFilesOperation CreateOperation(List<VerifyCacheFileElement> elements)
public static VerifyCacheFilesOperation CreateOperation(CacheManager cache, List<VerifyCacheFileElement> elements)
{
#if UNITY_WEBGL
var operation = new VerifyCacheFilesWithoutThreadOperation(elements);
var operation = new VerifyCacheFilesWithoutThreadOperation(cache, elements);
#else
var operation = new VerifyCacheFilesWithThreadOperation(elements);
var operation = new VerifyCacheFilesWithThreadOperation(cache, elements);
#endif
return operation;
}
@@ -33,6 +33,7 @@ namespace YooAsset
}
private readonly ThreadSyncContext _syncContext = new ThreadSyncContext();
private readonly CacheManager _cache;
private List<VerifyCacheFileElement> _waitingList;
private List<VerifyCacheFileElement> _verifyingList;
private int _verifyMaxNum;
@@ -42,8 +43,9 @@ namespace YooAsset
private int _failedCount;
private ESteps _steps = ESteps.None;
public VerifyCacheFilesWithThreadOperation(List<VerifyCacheFileElement> elements)
public VerifyCacheFilesWithThreadOperation(CacheManager cache, List<VerifyCacheFileElement> elements)
{
_cache = cache;
_waitingList = elements;
}
internal override void Start()
@@ -121,7 +123,7 @@ namespace YooAsset
private void VerifyInThread(object obj)
{
VerifyCacheFileElement element = (VerifyCacheFileElement)obj;
element.Result = CacheSystem.VerifyingCacheFile(element);
element.Result = CacheHelper.VerifyingCacheFile(element, _cache.BootVerifyLevel);
_syncContext.Post(VerifyCallback, element);
}
private void VerifyCallback(object obj)
@@ -132,8 +134,8 @@ namespace YooAsset
if (element.Result == EVerifyResult.Succeed)
{
_succeedCount++;
var wrapper = new PackageCache.RecordWrapper(element.InfoFilePath, element.DataFilePath, element.DataFileCRC, element.DataFileSize);
CacheSystem.RecordFile(element.PackageName, element.CacheGUID, wrapper);
var wrapper = new CacheManager.RecordWrapper(element.InfoFilePath, element.DataFilePath, element.DataFileCRC, element.DataFileSize);
_cache.Record(element.CacheGUID, wrapper);
}
else
{
@@ -158,6 +160,7 @@ namespace YooAsset
Done,
}
private readonly CacheManager _cache;
private List<VerifyCacheFileElement> _waitingList;
private List<VerifyCacheFileElement> _verifyingList;
private int _verifyMaxNum;
@@ -167,8 +170,9 @@ namespace YooAsset
private int _failedCount;
private ESteps _steps = ESteps.None;
public VerifyCacheFilesWithoutThreadOperation(List<VerifyCacheFileElement> elements)
public VerifyCacheFilesWithoutThreadOperation(CacheManager cache, List<VerifyCacheFileElement> elements)
{
_cache = cache;
_waitingList = elements;
}
internal override void Start()
@@ -231,12 +235,12 @@ namespace YooAsset
}
private void BeginVerifyFileWithoutThread(VerifyCacheFileElement element)
{
element.Result = CacheSystem.VerifyingCacheFile(element);
element.Result = CacheHelper.VerifyingCacheFile(element, _cache.BootVerifyLevel);
if (element.Result == EVerifyResult.Succeed)
{
_succeedCount++;
var wrapper = new PackageCache.RecordWrapper(element.InfoFilePath, element.DataFilePath, element.DataFileCRC, element.DataFileSize);
CacheSystem.RecordFile(element.PackageName, element.CacheGUID, wrapper);
var wrapper = new CacheManager.RecordWrapper(element.InfoFilePath, element.DataFilePath, element.DataFileCRC, element.DataFileSize);
_cache.Record(element.CacheGUID, wrapper);
}
else
{
@@ -86,7 +86,7 @@ namespace YooAsset
private void VerifyInThread(object obj)
{
VerifyTempFileElement element = (VerifyTempFileElement)obj;
int result = (int)CacheSystem.VerifyingTempFile(element);
int result = (int)CacheHelper.VerifyingTempFile(element);
element.Result = result;
}
}
@@ -121,7 +121,7 @@ namespace YooAsset
if (_steps == ESteps.VerifyFile)
{
_element.Result = (int)CacheSystem.VerifyingTempFile(_element);
_element.Result = (int)CacheHelper.VerifyingTempFile(_element);
VerifyResult = (EVerifyResult)_element.Result;
if (VerifyResult == EVerifyResult.Succeed)
@@ -15,14 +15,16 @@ namespace YooAsset
Done,
}
private readonly string _packageName;
private readonly PersistentManager _persistent;
private readonly CacheManager _cache;
private FindCacheFilesOperation _findCacheFilesOp;
private VerifyCacheFilesOperation _verifyCacheFilesOp;
private ESteps _steps = ESteps.None;
public PackageCachingOperation(string packageName)
public PackageCachingOperation(PersistentManager persistent, CacheManager cache)
{
_packageName = packageName;
_persistent = persistent;
_cache = cache;
}
internal override void Start()
{
@@ -37,8 +39,8 @@ namespace YooAsset
{
if (_findCacheFilesOp == null)
{
_findCacheFilesOp = new FindCacheFilesOperation(_packageName);
OperationSystem.StartOperation(_findCacheFilesOp);
_findCacheFilesOp = new FindCacheFilesOperation(_persistent, _cache);
OperationSystem.StartOperation(_cache.PackageName, _findCacheFilesOp);
}
Progress = _findCacheFilesOp.Progress;
@@ -52,8 +54,8 @@ namespace YooAsset
{
if (_verifyCacheFilesOp == null)
{
_verifyCacheFilesOp = VerifyCacheFilesOperation.CreateOperation(_findCacheFilesOp.VerifyElements);
OperationSystem.StartOperation(_verifyCacheFilesOp);
_verifyCacheFilesOp = VerifyCacheFilesOperation.CreateOperation(_cache, _findCacheFilesOp.VerifyElements);
OperationSystem.StartOperation(_cache.PackageName, _verifyCacheFilesOp);
}
Progress = _verifyCacheFilesOp.Progress;
@@ -64,8 +66,8 @@ namespace YooAsset
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
int totalCount = CacheSystem.GetCachedFilesCount(_packageName);
YooLogger.Log($"Package '{_packageName}' cached files count : {totalCount}");
int totalCount = _cache.GetAllCachedFilesCount();
YooLogger.Log($"Package '{_cache.PackageName}' cached files count : {totalCount}");
}
}
}
@@ -1,175 +0,0 @@
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<VerifyCacheFileElement> VerifyElements = new List<VerifyCacheFileElement>(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 = PersistentTools.GetPersistent(_packageName).SandboxCacheBundleFilesRoot;
DirectoryInfo rootDirectory = new DirectoryInfo(rootPath);
if (rootDirectory.Exists)
{
var directorieInfos = rootDirectory.EnumerateDirectories();
_bundleFilesEnumerator = directorieInfos.GetEnumerator();
}
}
// RawFiles
{
string rootPath = PersistentTools.GetPersistent(_packageName).SandboxCacheRawFilesRoot;
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}";
VerifyCacheFileElement element = new VerifyCacheFileElement(_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}";
VerifyCacheFileElement element = new VerifyCacheFileElement(_packageName, cacheGUID, fileRootPath, dataFilePath, infoFilePath);
VerifyElements.Add(element);
}
if (OperationSystem.IsBusy)
break;
}
return isFindItem;
}
}
}
@@ -0,0 +1,24 @@
namespace YooAsset
{
internal static class PersistentHelper
{
/// <summary>
/// 获取WWW加载本地资源的路径
/// </summary>
public static string ConvertToWWWPath(string path)
{
#if UNITY_EDITOR
return StringUtility.Format("file:///{0}", path);
#elif UNITY_IPHONE
return StringUtility.Format("file://{0}", path);
#elif UNITY_ANDROID
return path;
#elif UNITY_STANDALONE
return StringUtility.Format("file:///{0}", path);
#elif UNITY_WEBGL
return path;
#endif
}
}
}
@@ -1,31 +1,43 @@
using System.IO;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset
{
internal class Persistent
internal class PersistentManager
{
private readonly string _packageName;
private readonly Dictionary<string, string> _cachedDataFilePaths = new Dictionary<string, string>(10000);
private readonly Dictionary<string, string> _cachedInfoFilePaths = new Dictionary<string, string>(10000);
private readonly Dictionary<string, string> _tempDataFilePaths = new Dictionary<string, string>(10000);
private readonly Dictionary<string, string> _buildinFilePaths = new Dictionary<string, string>(10000);
/// <summary>
/// 所属包裹
/// </summary>
public readonly string PackageName;
public string BuildinRoot { private set; get; }
public string BuildinPackageRoot { private set; get; }
public string SandboxRoot { private set; get; }
public string SandboxPackageRoot { private set; get; }
public string SandboxCacheBundleFilesRoot { private set; get; }
public string SandboxCacheRawFilesRoot { private set; get; }
public string SandboxCacheFilesRoot { private set; get; }
public string SandboxManifestFilesRoot { private set; get; }
public string SandboxAppFootPrintFilePath { private set; get; }
public bool AppendFileExtension { private set; get; }
public Persistent(string packageName)
public PersistentManager(string packageName)
{
_packageName = packageName;
PackageName = packageName;
}
/// <summary>
/// 重写根路径
/// 初始化
/// </summary>
public void OverwriteRootDirectory(string buildinRoot, string sandboxRoot)
public void Initialize(string buildinRoot, string sandboxRoot, bool appendFileExtension)
{
if (string.IsNullOrEmpty(buildinRoot))
BuildinRoot = CreateDefaultBuildinRoot();
@@ -37,12 +49,12 @@ namespace YooAsset
else
SandboxRoot = sandboxRoot;
BuildinPackageRoot = PathUtility.Combine(BuildinRoot, _packageName);
SandboxPackageRoot = PathUtility.Combine(SandboxRoot, _packageName);
SandboxCacheBundleFilesRoot = PathUtility.Combine(SandboxPackageRoot, YooAssetSettings.CachedBundleFileFolder);
SandboxCacheRawFilesRoot = PathUtility.Combine(SandboxPackageRoot, YooAssetSettings.CachedRawFileFolder);
BuildinPackageRoot = PathUtility.Combine(BuildinRoot, PackageName);
SandboxPackageRoot = PathUtility.Combine(SandboxRoot, PackageName);
SandboxCacheFilesRoot = PathUtility.Combine(SandboxPackageRoot, YooAssetSettings.CacheFilesFolderName);
SandboxManifestFilesRoot = PathUtility.Combine(SandboxPackageRoot, YooAssetSettings.ManifestFolderName);
SandboxAppFootPrintFilePath = PathUtility.Combine(SandboxPackageRoot, YooAssetSettings.AppFootPrintFileName);
AppendFileExtension = appendFileExtension;
}
private static string CreateDefaultBuildinRoot()
{
@@ -62,6 +74,47 @@ namespace YooAsset
#endif
}
public string GetCachedDataFilePath(PackageBundle bundle)
{
if (_cachedDataFilePaths.TryGetValue(bundle.CacheGUID, out string filePath) == false)
{
string folderName = bundle.FileHash.Substring(0, 2);
filePath = PathUtility.Combine(SandboxCacheFilesRoot, folderName, bundle.CacheGUID, YooAssetSettings.CacheBundleDataFileName);
if (AppendFileExtension)
filePath += bundle.FileExtension;
_cachedDataFilePaths.Add(bundle.CacheGUID, filePath);
}
return filePath;
}
public string GetCachedInfoFilePath(PackageBundle bundle)
{
if (_cachedInfoFilePaths.TryGetValue(bundle.CacheGUID, out string filePath) == false)
{
string folderName = bundle.FileHash.Substring(0, 2);
filePath = PathUtility.Combine(SandboxCacheFilesRoot, folderName, bundle.CacheGUID, YooAssetSettings.CacheBundleInfoFileName);
_cachedInfoFilePaths.Add(bundle.CacheGUID, filePath);
}
return filePath;
}
public string GetTempDataFilePath(PackageBundle bundle)
{
if (_tempDataFilePaths.TryGetValue(bundle.CacheGUID, out string filePath) == false)
{
string cachedDataFilePath = GetCachedDataFilePath(bundle);
filePath = $"{cachedDataFilePath}.temp";
_tempDataFilePaths.Add(bundle.CacheGUID, filePath);
}
return filePath;
}
public string GetBuildinFilePath(PackageBundle bundle)
{
if (_buildinFilePaths.TryGetValue(bundle.CacheGUID, out string filePath) == false)
{
filePath = PathUtility.Combine(BuildinPackageRoot, bundle.FileName);
_buildinFilePaths.Add(bundle.CacheGUID, filePath);
}
return filePath;
}
/// <summary>
/// 删除沙盒里的包裹目录
@@ -71,19 +124,14 @@ namespace YooAsset
if (Directory.Exists(SandboxPackageRoot))
Directory.Delete(SandboxPackageRoot, true);
}
/// <summary>
/// 删除沙盒内的缓存文件夹
/// </summary>
public void DeleteSandboxCacheFilesFolder()
{
// CacheBundleFiles
if (Directory.Exists(SandboxCacheBundleFilesRoot))
Directory.Delete(SandboxCacheBundleFilesRoot, true);
// CacheRawFiles
if (Directory.Exists(SandboxCacheRawFilesRoot))
Directory.Delete(SandboxCacheRawFilesRoot, true);
if (Directory.Exists(SandboxCacheFilesRoot))
Directory.Delete(SandboxCacheFilesRoot, true);
}
/// <summary>
@@ -101,7 +149,7 @@ namespace YooAsset
/// </summary>
public string GetSandboxPackageManifestFilePath(string packageVersion)
{
string fileName = YooAssetSettingsData.GetManifestBinaryFileName(_packageName, packageVersion);
string fileName = YooAssetSettingsData.GetManifestBinaryFileName(PackageName, packageVersion);
return PathUtility.Combine(SandboxManifestFilesRoot, fileName);
}
@@ -110,7 +158,7 @@ namespace YooAsset
/// </summary>
public string GetSandboxPackageHashFilePath(string packageVersion)
{
string fileName = YooAssetSettingsData.GetPackageHashFileName(_packageName, packageVersion);
string fileName = YooAssetSettingsData.GetPackageHashFileName(PackageName, packageVersion);
return PathUtility.Combine(SandboxManifestFilesRoot, fileName);
}
@@ -119,7 +167,7 @@ namespace YooAsset
/// </summary>
public string GetSandboxPackageVersionFilePath()
{
string fileName = YooAssetSettingsData.GetPackageVersionFileName(_packageName);
string fileName = YooAssetSettingsData.GetPackageVersionFileName(PackageName);
return PathUtility.Combine(SandboxManifestFilesRoot, fileName);
}
@@ -138,7 +186,7 @@ namespace YooAsset
/// </summary>
public string GetBuildinPackageManifestFilePath(string packageVersion)
{
string fileName = YooAssetSettingsData.GetManifestBinaryFileName(_packageName, packageVersion);
string fileName = YooAssetSettingsData.GetManifestBinaryFileName(PackageName, packageVersion);
return PathUtility.Combine(BuildinPackageRoot, fileName);
}
@@ -147,7 +195,7 @@ namespace YooAsset
/// </summary>
public string GetBuildinPackageHashFilePath(string packageVersion)
{
string fileName = YooAssetSettingsData.GetPackageHashFileName(_packageName, packageVersion);
string fileName = YooAssetSettingsData.GetPackageHashFileName(PackageName, packageVersion);
return PathUtility.Combine(BuildinPackageRoot, fileName);
}
@@ -156,7 +204,7 @@ namespace YooAsset
/// </summary>
public string GetBuildinPackageVersionFilePath()
{
string fileName = YooAssetSettingsData.GetPackageVersionFileName(_packageName);
string fileName = YooAssetSettingsData.GetPackageVersionFileName(PackageName);
return PathUtility.Combine(BuildinPackageRoot, fileName);
}
}
@@ -1,51 +0,0 @@
using System.IO;
using System.Collections.Generic;
namespace YooAsset
{
internal class PersistentTools
{
private static readonly Dictionary<string, Persistent> _persitentDic = new Dictionary<string, Persistent>(100);
/// <summary>
/// 获取包裹的持久化类
/// </summary>
public static Persistent GetPersistent(string packageName)
{
if (_persitentDic.ContainsKey(packageName) == false)
throw new System.Exception("Should never get here !");
return _persitentDic[packageName];
}
/// <summary>
/// 获取或创建包裹的持久化类
/// </summary>
public static Persistent GetOrCreatePersistent(string packageName)
{
if (_persitentDic.ContainsKey(packageName) == false)
{
Persistent persistent = new Persistent(packageName);
_persitentDic.Add(packageName, persistent);
}
return _persitentDic[packageName];
}
/// <summary>
/// 获取WWW加载本地资源的路径
/// </summary>
public static string ConvertToWWWPath(string path)
{
#if UNITY_EDITOR
return StringUtility.Format("file:///{0}", path);
#elif UNITY_IPHONE
return StringUtility.Format("file://{0}", path);
#elif UNITY_ANDROID
return path;
#elif UNITY_STANDALONE
return StringUtility.Format("file:///{0}", path);
#elif UNITY_WEBGL
return path;
#endif
}
}
}
@@ -28,14 +28,13 @@ namespace YooAsset
public void DeleteFiles()
{
if (File.Exists(DataFilePath))
try
{
File.Delete(DataFilePath);
Directory.Delete(FileRootPath, true);
}
if (File.Exists(InfoFilePath))
catch(System.Exception e)
{
File.Delete(InfoFilePath);
YooLogger.Warning($"Failed delete cache bundle folder : {e}");
}
}
}
@@ -0,0 +1,41 @@
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine.Networking;
namespace YooAsset
{
/// <summary>
/// 自定义下载器的请求委托
/// </summary>
public delegate UnityWebRequest DownloadRequestDelegate(string url);
internal static class DownloadHelper
{
/// <summary>
/// 下载失败后清理文件的HTTP错误码
/// </summary>
public static List<long> ClearFileResponseCodes { set; get; }
/// <summary>
/// 自定义下载器的请求委托
/// </summary>
public static DownloadRequestDelegate RequestDelegate = null;
/// <summary>
/// 创建一个新的网络请求
/// </summary>
public static UnityWebRequest NewRequest(string requestURL)
{
UnityWebRequest webRequest;
if (RequestDelegate != null)
webRequest = RequestDelegate.Invoke(requestURL);
else
webRequest = new UnityWebRequest(requestURL, UnityWebRequest.kHttpVerbGET);
return webRequest;
}
}
}
@@ -0,0 +1,132 @@
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Networking;
namespace YooAsset
{
/// <summary>
/// 1. 保证每一时刻资源文件只存在一个下载器
/// 2. 保证下载器下载完成后立刻验证并缓存
/// 3. 保证资源文件不会被重复下载
/// </summary>
internal class DownloadManager
{
private readonly Dictionary<string, DownloaderBase> _downloaders = new Dictionary<string, DownloaderBase>(1000);
private readonly List<string> _removeList = new List<string>(1000);
private uint _breakpointResumeFileSize;
/// <summary>
/// 所属包裹
/// </summary>
public readonly string PackageName;
public DownloadManager(string packageName)
{
PackageName = packageName;
}
/// <summary>
/// 初始化
/// </summary>
public void Initialize(uint breakpointResumeFileSize)
{
_breakpointResumeFileSize = breakpointResumeFileSize;
}
/// <summary>
/// 更新下载器
/// </summary>
public void Update()
{
// 更新下载器
_removeList.Clear();
foreach (var valuePair in _downloaders)
{
var downloader = valuePair.Value;
downloader.Update();
if (downloader.IsDone())
_removeList.Add(valuePair.Key);
}
// 移除下载器
foreach (var key in _removeList)
{
_downloaders.Remove(key);
}
}
/// <summary>
/// 销毁所有下载器
/// </summary>
public void DestroyAll()
{
foreach (var valuePair in _downloaders)
{
var downloader = valuePair.Value;
downloader.Abort();
}
_downloaders.Clear();
_removeList.Clear();
}
/// <summary>
/// 创建下载器
/// 注意:只有第一次请求的参数才有效
/// </summary>
public DownloaderBase CreateDownload(BundleInfo bundleInfo, int failedTryAgain, int timeout = 60)
{
// 查询存在的下载器
if (_downloaders.TryGetValue(bundleInfo.CachedDataFilePath, out var downloader))
return downloader;
// 如果资源已经缓存
if (bundleInfo.IsCached())
{
var completedDownloader = new CompletedDownloader(bundleInfo);
return completedDownloader;
}
// 创建新的下载器
YooLogger.Log($"Beginning to download bundle : {bundleInfo.Bundle.BundleName} URL : {bundleInfo.RemoteMainURL}");
#if UNITY_WEBGL
if (bundleInfo.Bundle.Buildpipeline == DefaultBuildPipeline.RawFileBuildPipelineName)
{
FileUtility.CreateFileDirectory(bundleInfo.CachedDataFilePath);
System.Type requesterType = typeof(FileGeneralRequest);
DownloaderBase newDownloader = new FileDownloader(bundleInfo, requesterType, failedTryAgain, timeout);
_downloaders.Add(bundleInfo.CachedDataFilePath, newDownloader);
return newDownloader;
}
else
{
System.Type requesterType = typeof(AssetBundleWebRequest);
WebDownloader newDownloader = new WebDownloader(bundleInfo, requesterType, failedTryAgain, timeout);
_downloaders.Add(bundleInfo.CachedDataFilePath, newDownloader);
return newDownloader;
}
#else
FileUtility.CreateFileDirectory(bundleInfo.CachedDataFilePath);
bool resumeDownload = bundleInfo.Bundle.FileSize >= _breakpointResumeFileSize;
if (resumeDownload)
{
System.Type requesterType = typeof(FileResumeRequest);
DownloaderBase newDownloader = new FileDownloader(bundleInfo, requesterType, failedTryAgain, timeout);
_downloaders.Add(bundleInfo.CachedDataFilePath, newDownloader);
return newDownloader;
}
else
{
System.Type requesterType = typeof(FileGeneralRequest);
DownloaderBase newDownloader = new FileDownloader(bundleInfo, requesterType, failedTryAgain, timeout);
_downloaders.Add(bundleInfo.CachedDataFilePath, newDownloader);
return newDownloader;
}
#endif
}
}
}
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 5e32c14ed62806b4189d20ad48ce7631
guid: 6fbbbfe01e018b241bf33469f870a4b8
MonoImporter:
externalObjects: {}
serializedVersion: 2
@@ -1,30 +0,0 @@
namespace YooAsset
{
public struct DownloadReport
{
/// <summary>
/// 下载进度(0f~1f)
/// </summary>
public float Progress;
/// <summary>
/// 需要下载的总字节数
/// </summary>
public ulong TotalSize;
/// <summary>
/// 已经下载的字节数
/// </summary>
public ulong DownloadedBytes;
public static DownloadReport CreateDefaultReport()
{
DownloadReport report = new DownloadReport();
report.Progress = 0f;
report.TotalSize = 0;
report.DownloadedBytes = 0;
return report;
}
}
}
@@ -0,0 +1,36 @@
namespace YooAsset
{
public struct DownloadStatus
{
/// <summary>
/// 下载是否完成
/// </summary>
public bool IsDone;
/// <summary>
/// 下载进度(0f~1f)
/// </summary>
public float Progress;
/// <summary>
/// 需要下载的总字节数
/// </summary>
public ulong TotalBytes;
/// <summary>
/// 已经下载的字节数
/// </summary>
public ulong DownloadedBytes;
public static DownloadStatus CreateDefaultStatus()
{
DownloadStatus status = new DownloadStatus();
status.IsDone = false;
status.Progress = 0f;
status.TotalBytes = 0;
status.DownloadedBytes = 0;
return status;
}
}
}
@@ -1,184 +0,0 @@
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine.Networking;
namespace YooAsset
{
/// <summary>
/// 自定义下载器的请求委托
/// </summary>
public delegate UnityWebRequest DownloadRequestDelegate(string url);
/// <summary>
/// 1. 保证每一时刻资源文件只存在一个下载器
/// 2. 保证下载器下载完成后立刻验证并缓存
/// 3. 保证资源文件不会被重复下载
/// </summary>
internal static class DownloadSystem
{
private static readonly Dictionary<string, DownloaderBase> _downloaderDic = new Dictionary<string, DownloaderBase>();
private static readonly List<string> _removeList = new List<string>(100);
/// <summary>
/// 自定义下载器的请求委托
/// </summary>
public static DownloadRequestDelegate RequestDelegate = null;
/// <summary>
/// 自定义的证书认证实例
/// </summary>
public static CertificateHandler CertificateHandlerInstance = null;
/// <summary>
/// 网络重定向次数
/// </summary>
public static int RedirectLimit { set; get; } = -1;
/// <summary>
/// 启用断点续传功能文件的最小字节数
/// </summary>
public static int BreakpointResumeFileSize { set; get; } = int.MaxValue;
/// <summary>
/// 下载失败后清理文件的HTTP错误码
/// </summary>
public static List<long> ClearFileResponseCodes { set; get; }
/// <summary>
/// 初始化下载器
/// </summary>
public static void Initialize()
{
}
/// <summary>
/// 更新下载器
/// </summary>
public static void Update()
{
// 更新下载器
_removeList.Clear();
foreach (var valuePair in _downloaderDic)
{
var downloader = valuePair.Value;
downloader.Update();
if (downloader.IsDone())
_removeList.Add(valuePair.Key);
}
// 移除下载器
foreach (var key in _removeList)
{
_downloaderDic.Remove(key);
}
}
/// <summary>
/// 销毁所有下载器
/// </summary>
public static void DestroyAll()
{
foreach (var valuePair in _downloaderDic)
{
var downloader = valuePair.Value;
downloader.Abort();
}
_downloaderDic.Clear();
_removeList.Clear();
RequestDelegate = null;
CertificateHandlerInstance = null;
BreakpointResumeFileSize = int.MaxValue;
ClearFileResponseCodes = null;
}
/// <summary>
/// 创建下载器
/// 注意:只有第一次请求的参数才有效
/// </summary>
public static DownloaderBase CreateDownload(BundleInfo bundleInfo, int failedTryAgain, int timeout = 60)
{
// 查询存在的下载器
if (_downloaderDic.TryGetValue(bundleInfo.Bundle.CachedDataFilePath, out var downloader))
return downloader;
// 如果资源已经缓存
if (CacheSystem.IsCached(bundleInfo.Bundle.PackageName, bundleInfo.Bundle.CacheGUID))
{
var completedDownloader = new CompletedDownloader(bundleInfo);
return completedDownloader;
}
// 创建新的下载器
YooLogger.Log($"Beginning to download bundle : {bundleInfo.Bundle.BundleName} URL : {bundleInfo.RemoteMainURL}");
#if UNITY_WEBGL
if (bundleInfo.Bundle.IsRawFile)
{
FileUtility.CreateFileDirectory(bundleInfo.Bundle.CachedDataFilePath);
DownloaderBase newDownloader = new FileGeneralDownloader(bundleInfo, failedTryAgain, timeout);
_downloaderDic.Add(bundleInfo.Bundle.CachedDataFilePath, newDownloader);
return newDownloader;
}
else
{
WebDownloader newDownloader = new WebDownloader(bundleInfo, failedTryAgain, timeout);
_downloaderDic.Add(bundleInfo.Bundle.CachedDataFilePath, newDownloader);
return newDownloader;
}
#else
FileUtility.CreateFileDirectory(bundleInfo.Bundle.CachedDataFilePath);
bool resumeDownload = bundleInfo.Bundle.FileSize >= BreakpointResumeFileSize;
DownloaderBase newDownloader;
if (resumeDownload)
newDownloader = new FileResumeDownloader(bundleInfo, failedTryAgain, timeout);
else
newDownloader = new FileGeneralDownloader(bundleInfo, failedTryAgain, timeout);
_downloaderDic.Add(bundleInfo.Bundle.CachedDataFilePath, newDownloader);
return newDownloader;
#endif
}
/// <summary>
/// 创建一个新的网络请求
/// </summary>
public static UnityWebRequest NewRequest(string requestURL)
{
UnityWebRequest webRequest;
if (RequestDelegate != null)
webRequest = RequestDelegate.Invoke(requestURL);
else
webRequest = new UnityWebRequest(requestURL, UnityWebRequest.kHttpVerbGET);
SetUnityWebRequestParam(webRequest);
return webRequest;
}
/// <summary>
/// 设置网络请求的自定义参数
/// </summary>
private static void SetUnityWebRequestParam(UnityWebRequest webRequest)
{
if (RedirectLimit >= 0)
webRequest.redirectLimit = RedirectLimit;
if (CertificateHandlerInstance != null)
{
webRequest.certificateHandler = CertificateHandlerInstance;
webRequest.disposeCertificateHandlerOnDispose = false;
}
}
/// <summary>
/// 获取下载器的总数
/// </summary>
public static int GetDownloaderTotalCount()
{
return _downloaderDic.Count;
}
}
}
@@ -1,12 +1,14 @@
using UnityEngine;
namespace YooAsset
{
internal sealed class CompletedDownloader : DownloaderBase
{
public CompletedDownloader(BundleInfo bundleInfo) : base(bundleInfo, 0, 0)
public CompletedDownloader(BundleInfo bundleInfo) : base(bundleInfo, null, 0, 0)
{
_downloadProgress = 1f;
_downloadedBytes = (ulong)bundleInfo.Bundle.FileSize;
DownloadProgress = 1f;
DownloadedBytes = (ulong)bundleInfo.Bundle.FileSize;
_status = EStatus.Succeed;
}
@@ -19,5 +21,9 @@ namespace YooAsset
public override void Abort()
{
}
public override AssetBundle GetAssetBundle()
{
throw new System.NotImplementedException();
}
}
}
@@ -1,4 +1,4 @@
using System.IO;
using System;
using UnityEngine;
using UnityEngine.Networking;
@@ -14,22 +14,19 @@ namespace YooAsset
}
protected readonly BundleInfo _bundleInfo;
protected readonly System.Type _requesterType;
protected readonly int _timeout;
protected int _failedTryAgain;
protected UnityWebRequest _webRequest;
protected IWebRequester _requester;
protected EStatus _status = EStatus.None;
protected string _lastError = string.Empty;
protected long _lastCode = 0;
protected string _lastestNetError = string.Empty;
protected long _lastestHttpCode = 0;
// 请求次数
protected int _requestCount = 0;
protected string _requestURL;
// 下载进度
protected float _downloadProgress = 0f;
protected ulong _downloadedBytes = 0;
// 超时相关
protected bool _isAbort = false;
protected ulong _latestDownloadBytes;
@@ -45,29 +42,25 @@ namespace YooAsset
/// <summary>
/// 下载进度(0f~1f)
/// </summary>
public float DownloadProgress
{
get { return _downloadProgress; }
}
public float DownloadProgress { protected set; get; }
/// <summary>
/// 已经下载的总字节数
/// </summary>
public ulong DownloadedBytes
{
get { return _downloadedBytes; }
}
public ulong DownloadedBytes { protected set; get; }
public DownloaderBase(BundleInfo bundleInfo, int failedTryAgain, int timeout)
public DownloaderBase(BundleInfo bundleInfo, System.Type requesterType, int failedTryAgain, int timeout)
{
_bundleInfo = bundleInfo;
_requesterType = requesterType;
_failedTryAgain = failedTryAgain;
_timeout = timeout;
}
public abstract void SendRequest(params object[] param);
public abstract void SendRequest(params object[] args);
public abstract void Update();
public abstract void Abort();
public abstract AssetBundle GetAssetBundle();
/// <summary>
/// 获取下载文件的大小
@@ -123,7 +116,7 @@ namespace YooAsset
/// </summary>
public string GetLastError()
{
return $"Failed to download : {_requestURL} Error : {_lastError} Code : {_lastCode}";
return $"Failed to download : {_requestURL} Error : {_lastestNetError} Code : {_lastestHttpCode}";
}
@@ -158,36 +151,11 @@ namespace YooAsset
if (offset > _timeout)
{
YooLogger.Warning($"Web file request timeout : {_requestURL}");
_webRequest.Abort();
if(_requester != null)
_requester.Abort();
_isAbort = true;
}
}
}
/// <summary>
/// 缓存下载文件
/// </summary>
protected void CachingFile(string tempFilePath)
{
string infoFilePath = _bundleInfo.Bundle.CachedInfoFilePath;
string dataFilePath = _bundleInfo.Bundle.CachedDataFilePath;
string dataFileCRC = _bundleInfo.Bundle.FileCRC;
long dataFileSize = _bundleInfo.Bundle.FileSize;
if (File.Exists(infoFilePath))
File.Delete(infoFilePath);
if (File.Exists(dataFilePath))
File.Delete(dataFilePath);
FileInfo fileInfo = new FileInfo(tempFilePath);
fileInfo.MoveTo(dataFilePath);
// 写入信息文件记录验证数据
CacheFileInfo.WriteInfoToFile(infoFilePath, dataFileCRC, dataFileSize);
// 记录缓存文件
var wrapper = new PackageCache.RecordWrapper(infoFilePath, dataFilePath, dataFileCRC, dataFileSize);
CacheSystem.RecordFile(_bundleInfo.Bundle.PackageName, _bundleInfo.Bundle.CacheGUID, wrapper);
}
}
}
@@ -3,14 +3,13 @@ using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
namespace YooAsset
{
/// <summary>
/// 普通的下载器
/// 文件下载器
/// </summary>
internal sealed class FileGeneralDownloader : DownloaderBase
internal sealed class FileDownloader : DownloaderBase
{
private enum ESteps
{
@@ -25,16 +24,13 @@ namespace YooAsset
Done,
}
private readonly string _tempFilePath;
private VerifyTempFileOperation _verifyFileOp = null;
private ESteps _steps = ESteps.None;
public FileGeneralDownloader(BundleInfo bundleInfo, int failedTryAgain, int timeout) : base(bundleInfo, failedTryAgain, timeout)
public FileDownloader(BundleInfo bundleInfo, System.Type requesterType, int failedTryAgain, int timeout) : base(bundleInfo, requesterType, failedTryAgain, timeout)
{
_tempFilePath = bundleInfo.Bundle.TempDataFilePath;
}
public override void SendRequest(params object[] param)
public override void SendRequest(params object[] args)
{
if (_steps == ESteps.None)
{
@@ -55,8 +51,8 @@ namespace YooAsset
_requestURL = GetRequestURL();
// 重置变量
_downloadProgress = 0f;
_downloadedBytes = 0;
DownloadProgress = 0f;
DownloadedBytes = 0;
// 重置变量
_isAbort = false;
@@ -64,83 +60,51 @@ namespace YooAsset
_latestDownloadRealtime = Time.realtimeSinceStartup;
// 重置计时器
if(_tryAgainTimer > 0f)
if (_tryAgainTimer > 0f)
YooLogger.Warning($"Try again download : {_requestURL}");
_tryAgainTimer = 0f;
// 删除临时文件
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
_steps = ESteps.CreateDownloader;
}
// 创建下载器
if (_steps == ESteps.CreateDownloader)
{
_webRequest = DownloadSystem.NewRequest(_requestURL);
DownloadHandlerFile handler = new DownloadHandlerFile(_tempFilePath);
handler.removeFileOnAbort = true;
_webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true;
_webRequest.SendWebRequest();
_requester = (IWebRequester)Activator.CreateInstance(_requesterType);
_requester.Create(_requestURL, _bundleInfo);
_steps = ESteps.CheckDownload;
}
// 检测下载结果
if (_steps == ESteps.CheckDownload)
{
_downloadProgress = _webRequest.downloadProgress;
_downloadedBytes = _webRequest.downloadedBytes;
if (_webRequest.isDone == false)
_requester.Update();
DownloadedBytes = _requester.DownloadedBytes;
DownloadProgress = _requester.DownloadProgress;
if (_requester.IsDone() == false)
{
CheckTimeout();
return;
}
bool hasError = false;
// 检查网络错误
#if UNITY_2020_3_OR_NEWER
if (_webRequest.result != UnityWebRequest.Result.Success)
_lastestNetError = _requester.RequestNetError;
_lastestHttpCode = _requester.RequestHttpCode;
if (_requester.Status != ERequestStatus.Success)
{
hasError = true;
_lastError = _webRequest.error;
_lastCode = _webRequest.responseCode;
}
#else
if (_webRequest.isNetworkError || _webRequest.isHttpError)
{
hasError = true;
_lastError = _webRequest.error;
_lastCode = _webRequest.responseCode;
}
#endif
// 如果网络异常
if (hasError)
{
// 下载失败之后删除文件
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
_steps = ESteps.TryAgain;
}
else
{
_steps = ESteps.VerifyTempFile;
}
// 最终释放下载器
DisposeWebRequest();
}
// 验证下载文件
if (_steps == ESteps.VerifyTempFile)
{
VerifyTempFileElement element = new VerifyTempFileElement(_bundleInfo.Bundle.TempDataFilePath, _bundleInfo.Bundle.FileCRC, _bundleInfo.Bundle.FileSize);
VerifyTempFileElement element = new VerifyTempFileElement(_bundleInfo.TempDataFilePath, _bundleInfo.Bundle.FileCRC, _bundleInfo.Bundle.FileSize);
_verifyFileOp = VerifyTempFileOperation.CreateOperation(element);
OperationSystem.StartOperation(_verifyFileOp);
OperationSystem.StartOperation(_bundleInfo.Bundle.PackageName, _verifyFileOp);
_steps = ESteps.WaitingVerifyTempFile;
}
@@ -159,10 +123,11 @@ namespace YooAsset
}
else
{
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
string tempFilePath = _bundleInfo.TempDataFilePath;
if (File.Exists(tempFilePath))
File.Delete(tempFilePath);
_lastError = _verifyFileOp.Error;
_lastestNetError = _verifyFileOp.Error;
_steps = ESteps.TryAgain;
}
}
@@ -172,15 +137,13 @@ namespace YooAsset
{
try
{
CachingFile(_tempFilePath);
CachingFile();
_status = EStatus.Succeed;
_steps = ESteps.Done;
_lastError = string.Empty;
_lastCode = 0;
}
catch (Exception e)
{
_lastError = e.Message;
_lastestNetError = e.Message;
_steps = ESteps.TryAgain;
}
}
@@ -207,23 +170,47 @@ namespace YooAsset
}
public override void Abort()
{
if (_requester != null)
_requester.Abort();
if (IsDone() == false)
{
_status = EStatus.Failed;
_steps = ESteps.Done;
_lastError = "user abort";
_lastCode = 0;
DisposeWebRequest();
_lastestNetError = "user abort";
_lastestHttpCode = 0;
}
}
private void DisposeWebRequest()
public override AssetBundle GetAssetBundle()
{
if (_webRequest != null)
{
_webRequest.Dispose();
_webRequest = null;
}
throw new NotImplementedException();
}
/// <summary>
/// 缓存下载文件
/// </summary>
private void CachingFile()
{
string tempFilePath = _bundleInfo.TempDataFilePath;
string infoFilePath = _bundleInfo.CachedInfoFilePath;
string dataFilePath = _bundleInfo.CachedDataFilePath;
string dataFileCRC = _bundleInfo.Bundle.FileCRC;
long dataFileSize = _bundleInfo.Bundle.FileSize;
if (File.Exists(infoFilePath))
File.Delete(infoFilePath);
if (File.Exists(dataFilePath))
File.Delete(dataFilePath);
// 移动临时文件路径
FileInfo fileInfo = new FileInfo(tempFilePath);
fileInfo.MoveTo(dataFilePath);
// 写入信息文件记录验证数据
CacheFileInfo.WriteInfoToFile(infoFilePath, dataFileCRC, dataFileSize);
// 记录缓存文件
_bundleInfo.CacheRecord();
}
}
}
@@ -1,295 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
namespace YooAsset
{
/// <summary>
/// 断点续传下载器
/// </summary>
internal sealed class FileResumeDownloader : DownloaderBase
{
private enum ESteps
{
None,
CheckTempFile,
WaitingCheckTempFile,
PrepareDownload,
CreateDownloader,
CheckDownload,
VerifyTempFile,
WaitingVerifyTempFile,
CachingFile,
TryAgain,
Done,
}
private readonly string _tempFilePath;
private DownloadHandlerFileRange _downloadHandle = null;
private VerifyTempFileOperation _checkFileOp = null;
private VerifyTempFileOperation _verifyFileOp = null;
private ESteps _steps = ESteps.None;
// 重置变量
private ulong _fileOriginLength;
public FileResumeDownloader(BundleInfo bundleInfo, int failedTryAgain, int timeout) : base(bundleInfo, failedTryAgain, timeout)
{
_tempFilePath = bundleInfo.Bundle.TempDataFilePath;
}
public override void SendRequest(params object[] param)
{
if (_steps == ESteps.None)
{
_steps = ESteps.CheckTempFile;
}
}
public override void Update()
{
if (_steps == ESteps.None)
return;
if (IsDone())
return;
// 检测临时文件
if (_steps == ESteps.CheckTempFile)
{
VerifyTempFileElement element = new VerifyTempFileElement(_bundleInfo.Bundle.TempDataFilePath, _bundleInfo.Bundle.FileCRC, _bundleInfo.Bundle.FileSize);
_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;
}
else
{
if (_checkFileOp.VerifyResult == EVerifyResult.FileOverflow)
{
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
}
_steps = ESteps.PrepareDownload;
}
}
// 创建下载器
if (_steps == ESteps.PrepareDownload)
{
// 获取请求地址
_requestURL = GetRequestURL();
// 重置变量
_downloadProgress = 0f;
_downloadedBytes = 0;
// 重置变量
_isAbort = false;
_latestDownloadBytes = 0;
_latestDownloadRealtime = Time.realtimeSinceStartup;
_fileOriginLength = 0;
// 重置计时器
if (_tryAgainTimer > 0f)
YooLogger.Warning($"Try again download : {_requestURL}");
_tryAgainTimer = 0f;
_steps = ESteps.CreateDownloader;
}
// 创建下载器
if (_steps == ESteps.CreateDownloader)
{
long fileLength = -1;
if (File.Exists(_tempFilePath))
{
FileInfo fileInfo = new FileInfo(_tempFilePath);
fileLength = fileInfo.Length;
_fileOriginLength = (ulong)fileLength;
_downloadedBytes = _fileOriginLength;
}
#if UNITY_2019_4_OR_NEWER
_webRequest = DownloadSystem.NewRequest(_requestURL);
var handler = new DownloadHandlerFile(_tempFilePath, true);
handler.removeFileOnAbort = false;
#else
_webRequest = DownloadSystem.NewRequest(_requestURL);
var handler = new DownloadHandlerFileRange(_tempFilePath, _bundleInfo.Bundle.FileSize, _webRequest);
_downloadHandle = handler;
#endif
_webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true;
if (fileLength > 0)
_webRequest.SetRequestHeader("Range", $"bytes={fileLength}-");
_webRequest.SendWebRequest();
_steps = ESteps.CheckDownload;
}
// 检测下载结果
if (_steps == ESteps.CheckDownload)
{
_downloadProgress = _webRequest.downloadProgress;
_downloadedBytes = _fileOriginLength + _webRequest.downloadedBytes;
if (_webRequest.isDone == false)
{
CheckTimeout();
return;
}
bool hasError = false;
// 检查网络错误
#if UNITY_2020_3_OR_NEWER
if (_webRequest.result != UnityWebRequest.Result.Success)
{
hasError = true;
_lastError = _webRequest.error;
_lastCode = _webRequest.responseCode;
}
#else
if (_webRequest.isNetworkError || _webRequest.isHttpError)
{
hasError = true;
_lastError = _webRequest.error;
_lastCode = _webRequest.responseCode;
}
#endif
// 如果网络异常
if (hasError)
{
// 注意:下载断点续传文件发生特殊错误码之后删除文件
if (DownloadSystem.ClearFileResponseCodes != null)
{
if (DownloadSystem.ClearFileResponseCodes.Contains(_webRequest.responseCode))
{
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
}
}
_steps = ESteps.TryAgain;
}
else
{
_steps = ESteps.VerifyTempFile;
}
// 最终释放下载器
DisposeWebRequest();
}
// 验证下载文件
if (_steps == ESteps.VerifyTempFile)
{
VerifyTempFileElement element = new VerifyTempFileElement(_bundleInfo.Bundle.TempDataFilePath, _bundleInfo.Bundle.FileCRC, _bundleInfo.Bundle.FileSize);
_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;
}
else
{
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
_lastError = _verifyFileOp.Error;
_steps = ESteps.TryAgain;
}
}
// 缓存下载文件
if (_steps == ESteps.CachingFile)
{
try
{
CachingFile(_tempFilePath);
_status = EStatus.Succeed;
_steps = ESteps.Done;
_lastError = string.Empty;
_lastCode = 0;
}
catch (Exception e)
{
_lastError = e.Message;
_steps = ESteps.TryAgain;
}
}
// 重新尝试下载
if (_steps == ESteps.TryAgain)
{
if (_failedTryAgain <= 0)
{
ReportError();
_status = EStatus.Failed;
_steps = ESteps.Done;
return;
}
_tryAgainTimer += Time.unscaledDeltaTime;
if (_tryAgainTimer > 1f)
{
_failedTryAgain--;
_steps = ESteps.PrepareDownload;
ReportWarning();
}
}
}
public override void Abort()
{
if (IsDone() == false)
{
_status = EStatus.Failed;
_steps = ESteps.Done;
_lastError = "user abort";
_lastCode = 0;
DisposeWebRequest();
}
}
private void DisposeWebRequest()
{
if (_downloadHandle != null)
{
_downloadHandle.Cleanup();
_downloadHandle = null;
}
if (_webRequest != null)
{
_webRequest.Dispose();
_webRequest = null;
}
}
}
}
@@ -3,7 +3,6 @@ using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
namespace YooAsset
{
@@ -15,26 +14,21 @@ namespace YooAsset
PrepareDownload,
CreateDownloader,
CheckDownload,
VerifyTempFile,
WaitingVerifyTempFile,
CachingFile,
TryAgain,
Done,
}
private bool _keepDownloadHandleLife = false;
private DownloadHandlerAssetBundle _downloadhandler;
private ESteps _steps = ESteps.None;
private bool _getAssetBundle;
public WebDownloader(BundleInfo bundleInfo, int failedTryAgain, int timeout) : base(bundleInfo, failedTryAgain, timeout)
public WebDownloader(BundleInfo bundleInfo, System.Type requesterType, int failedTryAgain, int timeout) : base(bundleInfo, requesterType, failedTryAgain, timeout)
{
}
public override void SendRequest(params object[] param)
public override void SendRequest(params object[] args)
{
if (_steps == ESteps.None)
{
_keepDownloadHandleLife = (bool)param[0];
_getAssetBundle = (bool)args[0];
_steps = ESteps.PrepareDownload;
}
}
@@ -48,82 +42,49 @@ namespace YooAsset
// 创建下载器
if (_steps == ESteps.PrepareDownload)
{
// 获取请求地址
_requestURL = GetRequestURL();
// 重置变量
_downloadProgress = 0f;
_downloadedBytes = 0;
DownloadProgress = 0f;
DownloadedBytes = 0;
// 重置变量
_isAbort = false;
_latestDownloadBytes = 0;
_latestDownloadRealtime = Time.realtimeSinceStartup;
// 重置计时器
if (_tryAgainTimer > 0f)
YooLogger.Warning($"Try again download : {_requestURL}");
_tryAgainTimer = 0f;
// 获取请求地址
_requestURL = GetRequestURL();
_steps = ESteps.CreateDownloader;
}
// 创建下载器
if (_steps == ESteps.CreateDownloader)
{
_webRequest = DownloadSystem.NewRequest(_requestURL);
if (CacheSystem.DisableUnityCacheOnWebGL)
{
uint crc = _bundleInfo.Bundle.UnityCRC;
_downloadhandler = new DownloadHandlerAssetBundle(_requestURL, crc);
#if UNITY_2020_3_OR_NEWER
_downloadhandler.autoLoadAssetBundle = false;
#endif
}
else
{
uint crc = _bundleInfo.Bundle.UnityCRC;
var hash = Hash128.Parse(_bundleInfo.Bundle.FileHash);
_downloadhandler = new DownloadHandlerAssetBundle(_requestURL, hash, crc);
#if UNITY_2020_3_OR_NEWER
_downloadhandler.autoLoadAssetBundle = false;
#endif
}
_webRequest.downloadHandler = _downloadhandler;
_webRequest.disposeDownloadHandlerOnDispose = false;
_webRequest.SendWebRequest();
_requester = (IWebRequester)Activator.CreateInstance(_requesterType);
_requester.Create(_requestURL, _bundleInfo, _getAssetBundle);
_steps = ESteps.CheckDownload;
}
// 检测下载结果
if (_steps == ESteps.CheckDownload)
{
_downloadProgress = _webRequest.downloadProgress;
_downloadedBytes = _webRequest.downloadedBytes;
if (_webRequest.isDone == false)
_requester.Update();
DownloadedBytes = _requester.DownloadedBytes;
DownloadProgress = _requester.DownloadProgress;
if (_requester.IsDone() == false)
{
CheckTimeout();
return;
}
bool hasError = false;
// 检查网络错误
#if UNITY_2020_3_OR_NEWER
if (_webRequest.result != UnityWebRequest.Result.Success)
{
hasError = true;
_lastError = _webRequest.error;
_lastCode = _webRequest.responseCode;
}
#else
if (_webRequest.isNetworkError || _webRequest.isHttpError)
{
hasError = true;
_lastError = _webRequest.error;
_lastCode = _webRequest.responseCode;
}
#endif
// 如果网络异常
if (hasError)
_lastestNetError = _requester.RequestNetError;
_lastestHttpCode = _requester.RequestHttpCode;
if (_requester.Status != ERequestStatus.Success)
{
_steps = ESteps.TryAgain;
}
@@ -131,15 +92,7 @@ namespace YooAsset
{
_status = EStatus.Succeed;
_steps = ESteps.Done;
_lastError = string.Empty;
_lastCode = 0;
}
// 最终释放请求
DisposeRequest();
if (_keepDownloadHandleLife == false)
DisposeHandler();
}
// 重新尝试下载
@@ -147,8 +100,6 @@ namespace YooAsset
{
if (_failedTryAgain <= 0)
{
DisposeRequest();
DisposeHandler();
ReportError();
_status = EStatus.Failed;
_steps = ESteps.Done;
@@ -167,47 +118,20 @@ namespace YooAsset
}
public override void Abort()
{
if (_requester != null)
_requester.Abort();
if (IsDone() == false)
{
_status = EStatus.Failed;
_steps = ESteps.Done;
_lastError = "user abort";
_lastCode = 0;
DisposeRequest();
DisposeHandler();
_lastestNetError = "user abort";
_lastestHttpCode = 0;
}
}
private void DisposeRequest()
public override AssetBundle GetAssetBundle()
{
if (_webRequest != null)
{
_webRequest.Dispose();
_webRequest = null;
}
}
/// <summary>
/// 获取资源包
/// </summary>
public AssetBundle GetAssetBundle()
{
if (_downloadhandler != null)
return _downloadhandler.assetBundle;
return null;
}
/// <summary>
/// 释放下载句柄
/// </summary>
public void DisposeHandler()
{
if (_downloadhandler != null)
{
_downloadhandler.Dispose();
_downloadhandler = null;
}
return (AssetBundle)_requester.GetRequestObject();
}
}
}
@@ -0,0 +1,36 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset
{
public class RemoteTools
{
/// <summary>
/// 记录网络请求失败事件的次数
/// </summary>
private static readonly Dictionary<string, int> _requestFailedRecorder = new Dictionary<string, int>(1000);
/// <summary>
/// 记录请求失败事件
/// </summary>
public static void RecordRequestFailed(string packageName, string eventName)
{
string key = $"{packageName}_{eventName}";
if (_requestFailedRecorder.ContainsKey(key) == false)
_requestFailedRecorder.Add(key, 0);
_requestFailedRecorder[key]++;
}
/// <summary>
/// 获取请求失败的次数
/// </summary>
public static int GetRequestFailedCount(string packageName, string eventName)
{
string key = $"{packageName}_{eventName}";
if (_requestFailedRecorder.ContainsKey(key) == false)
_requestFailedRecorder.Add(key, 0);
return _requestFailedRecorder[key];
}
}
}
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: a439c9a8f36dcc942b92a8e8af927237
guid: ca9b2c6456d21bb4e9eecd9dc820a641
MonoImporter:
externalObjects: {}
serializedVersion: 2
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 2de5a58f37a4ae64e804f150144da809
guid: 8a97534752300584a9b8c60c04c6a6a8
folderAsset: yes
DefaultImporter:
externalObjects: {}
@@ -0,0 +1,144 @@
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
namespace YooAsset
{
internal class AssetBundleWebRequest : IWebRequester
{
private UnityWebRequest _webRequest;
private DownloadHandlerAssetBundle _downloadhandler;
private AssetBundle _cacheAssetBundle;
private bool _getAssetBundle = false;
public ERequestStatus Status { private set; get; } = ERequestStatus.None;
public float DownloadProgress { private set; get; }
public ulong DownloadedBytes { private set; get; }
public string RequestNetError { private set; get; }
public long RequestHttpCode { private set; get; }
public void Create(string requestURL, BundleInfo bundleInfo, params object[] args)
{
if (Status != ERequestStatus.None)
throw new System.Exception("Should never get here !");
if (args.Length == 0)
throw new System.Exception("Not found param value");
// 解析附加参数
_getAssetBundle = (bool)args[0];
// 创建下载器
_webRequest = DownloadHelper.NewRequest(requestURL);
if (CacheHelper.DisableUnityCacheOnWebGL)
{
uint crc = bundleInfo.Bundle.UnityCRC;
_downloadhandler = new DownloadHandlerAssetBundle(requestURL, crc);
}
else
{
uint crc = bundleInfo.Bundle.UnityCRC;
var hash = Hash128.Parse(bundleInfo.Bundle.FileHash);
_downloadhandler = new DownloadHandlerAssetBundle(requestURL, hash, crc);
}
#if UNITY_2020_3_OR_NEWER
_downloadhandler.autoLoadAssetBundle = false;
#endif
_webRequest.downloadHandler = _downloadhandler;
_webRequest.disposeDownloadHandlerOnDispose = true;
_webRequest.SendWebRequest();
Status = ERequestStatus.InProgress;
}
public void Update()
{
if (Status == ERequestStatus.None)
return;
if (IsDone())
return;
DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = _webRequest.downloadedBytes;
if (_webRequest.isDone == false)
return;
// 检查网络错误
#if UNITY_2020_3_OR_NEWER
RequestHttpCode = _webRequest.responseCode;
if (_webRequest.result != UnityWebRequest.Result.Success)
{
RequestNetError = _webRequest.error;
Status = ERequestStatus.Error;
}
else
{
Status = ERequestStatus.Success;
}
#else
RequestHttpCode = _webRequest.responseCode;
if (_webRequest.isNetworkError || _webRequest.isHttpError)
{
RequestNetError = _webRequest.error;
Status = ERequestStatus.Error;
}
else
{
Status = ERequestStatus.Success;
}
#endif
// 缓存加载的AssetBundle对象
if (Status == ERequestStatus.Success)
{
if (_getAssetBundle)
{
_cacheAssetBundle = _downloadhandler.assetBundle;
if (_cacheAssetBundle == null)
{
RequestNetError = "assetBundle is null";
Status = ERequestStatus.Error;
}
}
}
// 最终释放下载器
DisposeWebRequest();
}
public void Abort()
{
// 如果下载任务还未开始
if (Status == ERequestStatus.None)
{
RequestNetError = "user cancel";
Status = ERequestStatus.Error;
}
else
{
// 注意:为了防止同一个文件强制停止之后立马创建新的请求,应该让进行中的请求自然终止。
if (_webRequest != null)
{
if (_webRequest.isDone == false)
_webRequest.Abort(); // If in progress, halts the UnityWebRequest as soon as possible.
}
}
}
public bool IsDone()
{
if (Status == ERequestStatus.Success || Status == ERequestStatus.Error)
return true;
else
return false;
}
public object GetRequestObject()
{
return _cacheAssetBundle;
}
private void DisposeWebRequest()
{
if (_webRequest != null)
{
_webRequest.Dispose();
_webRequest = null;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 34efa85440da15247b570a98b0971282
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,106 @@
using System.IO;
using UnityEngine.Networking;
namespace YooAsset
{
internal class FileGeneralRequest : IWebRequester
{
private UnityWebRequest _webRequest;
public ERequestStatus Status { private set; get; } = ERequestStatus.None;
public float DownloadProgress { private set; get; }
public ulong DownloadedBytes { private set; get; }
public string RequestNetError { private set; get; }
public long RequestHttpCode { private set; get; }
public void Create(string requestURL, BundleInfo bundleInfo, params object[] args)
{
if (Status != ERequestStatus.None)
throw new System.Exception("Should never get here !");
string tempFilePath = bundleInfo.TempDataFilePath;
// 删除临时文件
if (File.Exists(tempFilePath))
File.Delete(tempFilePath);
// 创建下载器
_webRequest = DownloadHelper.NewRequest(requestURL);
DownloadHandlerFile handler = new DownloadHandlerFile(tempFilePath);
handler.removeFileOnAbort = true;
_webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true;
_webRequest.SendWebRequest();
Status = ERequestStatus.InProgress;
}
public void Update()
{
if (Status == ERequestStatus.None)
return;
if (IsDone())
return;
DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = _webRequest.downloadedBytes;
if (_webRequest.isDone == false)
return;
// 检查网络错误
#if UNITY_2020_3_OR_NEWER
RequestHttpCode = _webRequest.responseCode;
if (_webRequest.result != UnityWebRequest.Result.Success)
{
RequestNetError = _webRequest.error;
Status = ERequestStatus.Error;
}
else
{
Status = ERequestStatus.Success;
}
#else
RequestHttpCode = _webRequest.responseCode;
if (_webRequest.isNetworkError || _webRequest.isHttpError)
{
RequestNetError = _webRequest.error;
Status = ERequestStatus.Error;
}
else
{
Status = ERequestStatus.Success;
}
#endif
// 最终释放下载器
DisposeWebRequest();
}
public void Abort()
{
DisposeWebRequest();
if (IsDone() == false)
{
RequestNetError = "user abort";
RequestHttpCode = 0;
Status = ERequestStatus.Error;
}
}
public bool IsDone()
{
if (Status == ERequestStatus.Success || Status == ERequestStatus.Error)
return true;
else
return false;
}
public object GetRequestObject()
{
throw new System.NotImplementedException();
}
private void DisposeWebRequest()
{
if (_webRequest != null)
{
_webRequest.Dispose(); //注意:引擎底层会自动调用Abort方法
_webRequest = null;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b2f339136a4269343a3b5ab80450b889
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,149 @@
using System.IO;
using UnityEngine.Networking;
namespace YooAsset
{
internal class FileResumeRequest : IWebRequester
{
private string _tempFilePath;
private UnityWebRequest _webRequest;
private DownloadHandlerFileRange _downloadHandle;
private ulong _fileOriginLength;
public ERequestStatus Status { private set; get; } = ERequestStatus.None;
public float DownloadProgress { private set; get; }
public ulong DownloadedBytes { private set; get; }
public string RequestNetError { private set; get; }
public long RequestHttpCode { private set; get; }
public void Create(string requestURL, BundleInfo bundleInfo, params object[] args)
{
if (Status != ERequestStatus.None)
throw new System.Exception("Should never get here !");
_tempFilePath = bundleInfo.TempDataFilePath;
long fileBytes = bundleInfo.Bundle.FileSize;
// 获取下载的起始位置
long fileLength = -1;
if (File.Exists(_tempFilePath))
{
FileInfo fileInfo = new FileInfo(_tempFilePath);
fileLength = fileInfo.Length;
_fileOriginLength = (ulong)fileLength;
DownloadedBytes = _fileOriginLength;
}
// 检测下载起始位置是否有效
if (fileLength >= fileBytes)
{
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
}
// 创建下载器
_webRequest = DownloadHelper.NewRequest(requestURL);
#if UNITY_2019_4_OR_NEWER
var handler = new DownloadHandlerFile(_tempFilePath, true);
handler.removeFileOnAbort = false;
#else
var handler = new DownloadHandlerFileRange(tempFilePath, _bundleInfo.Bundle.FileSize, _webRequest);
_downloadHandle = handler;
#endif
_webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true;
if (fileLength > 0)
_webRequest.SetRequestHeader("Range", $"bytes={fileLength}-");
_webRequest.SendWebRequest();
Status = ERequestStatus.InProgress;
}
public void Update()
{
if (Status == ERequestStatus.None)
return;
if (IsDone())
return;
DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = _fileOriginLength + _webRequest.downloadedBytes;
if (_webRequest.isDone == false)
return;
// 检查网络错误
#if UNITY_2020_3_OR_NEWER
RequestHttpCode = _webRequest.responseCode;
if (_webRequest.result != UnityWebRequest.Result.Success)
{
RequestNetError = _webRequest.error;
Status = ERequestStatus.Error;
}
else
{
Status = ERequestStatus.Success;
}
#else
RequestHttpCode = _webRequest.responseCode;
if (_webRequest.isNetworkError || _webRequest.isHttpError)
{
RequestNetError = _webRequest.error;
Status = ERequestStatus.Error;
}
else
{
Status = ERequestStatus.Success;
}
#endif
// 注意:下载断点续传文件发生特殊错误码之后删除文件
if (Status == ERequestStatus.Error)
{
if (DownloadHelper.ClearFileResponseCodes != null)
{
if (DownloadHelper.ClearFileResponseCodes.Contains(RequestHttpCode))
{
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
}
}
}
// 最终释放下载器
DisposeWebRequest();
}
public void Abort()
{
DisposeWebRequest();
if (IsDone() == false)
{
RequestNetError = "user abort";
RequestHttpCode = 0;
Status = ERequestStatus.Error;
}
}
public bool IsDone()
{
if (Status == ERequestStatus.Success || Status == ERequestStatus.Error)
return true;
else
return false;
}
public object GetRequestObject()
{
throw new System.NotImplementedException();
}
private void DisposeWebRequest()
{
if (_downloadHandle != null)
{
_downloadHandle.Cleanup();
_downloadHandle = null;
}
if (_webRequest != null)
{
_webRequest.Dispose();
_webRequest = null;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 816bf5396d7570e4ab28f1af407bc10f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,65 @@
namespace YooAsset
{
internal enum ERequestStatus
{
None,
InProgress,
Error,
Success,
}
internal interface IWebRequester
{
/// <summary>
/// 任务状态
/// </summary>
public ERequestStatus Status { get; }
/// <summary>
/// 下载进度(0f~1f)
/// </summary>
public float DownloadProgress { get; }
/// <summary>
/// 已经下载的总字节数
/// </summary>
public ulong DownloadedBytes { get; }
/// <summary>
/// 返回的网络错误
/// </summary>
public string RequestNetError { get; }
/// <summary>
/// 返回的HTTP CODE
/// </summary>
public long RequestHttpCode { get; }
/// <summary>
/// 创建任务
/// </summary>
public void Create(string url, BundleInfo bundleInfo, params object[] args);
/// <summary>
/// 更新任务
/// </summary>
public void Update();
/// <summary>
/// 终止任务
/// </summary>
public void Abort();
/// <summary>
/// 是否已经完成(无论成功或失败)
/// </summary>
public bool IsDone();
/// <summary>
/// 获取请求的对象
/// </summary>
public object GetRequestObject();
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4d80b965d56870b43af1bf6943015914
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -18,7 +18,7 @@ namespace YooAsset
URL = url;
ResetTimeout(timeout);
_webRequest = DownloadSystem.NewRequest(URL);
_webRequest = DownloadHelper.NewRequest(URL);
DownloadHandlerBuffer handler = new DownloadHandlerBuffer();
_webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true;
@@ -18,7 +18,7 @@ namespace YooAsset
URL = url;
ResetTimeout(timeout);
_webRequest = DownloadSystem.NewRequest(URL);
_webRequest = DownloadHelper.NewRequest(URL);
DownloadHandlerFile handler = new DownloadHandlerFile(fileSavePath);
handler.removeFileOnAbort = true;
_webRequest.downloadHandler = handler;
+42 -17
View File
@@ -1,6 +1,16 @@
namespace YooAsset
{
/// <summary>
/// 默认的构建管线
/// </summary>
public class DefaultBuildPipeline
{
public const string BuiltinBuildPipelineName = "BuiltinBuildPipeline";
public const string ScriptableBuildPipelineName = "ScriptableBuildPipeline";
public const string RawFileBuildPipelineName = "RawFileBuildPipeline";
}
/// <summary>
/// 运行模式
/// </summary>
@@ -32,11 +42,6 @@ namespace YooAsset
/// </summary>
public abstract class InitializeParameters
{
/// <summary>
/// 文件解密服务接口
/// </summary>
public IDecryptionServices DecryptionServices = null;
/// <summary>
/// 内置文件的根路径
/// 注意:当参数为空的时候会使用默认的根目录。
@@ -48,18 +53,33 @@ namespace YooAsset
/// 注意:当参数为空的时候会使用默认的根目录。
/// </summary>
public string SandboxRootDirectory = string.Empty;
/// <summary>
/// 缓存文件追加原始后缀格式
/// </summary>
public bool CacheFileAppendExtension = false;
/// <summary>
/// 缓存系统启动时的验证级别
/// </summary>
public EVerifyLevel CacheBootVerifyLevel = EVerifyLevel.Middle;
/// <summary>
/// 资源加载每帧处理的最大时间片段
/// 注意:默认值为MaxValue
/// </summary>
public long LoadingMaxTimeSlice = long.MaxValue;
/// <summary>
/// 下载失败尝试次数
/// 注意:默认值为MaxValue
/// 启用断点续传参数
/// 说明:当文件的大小大于设置的字节数时启用断点续传下载器
/// </summary>
public int DownloadFailedTryAgain = int.MaxValue;
public uint BreakpointResumeFileSize = int.MaxValue;
/// <summary>
/// 文件解密服务接口
/// </summary>
public IDecryptionServices DecryptionServices = null;
}
/// <summary>
@@ -85,6 +105,11 @@ namespace YooAsset
/// </summary>
public class HostPlayModeParameters : InitializeParameters
{
/// <summary>
/// 远端资源地址查询服务类
/// </summary>
public IRemoteServices RemoteServices = null;
/// <summary>
/// 内置资源查询服务接口
/// </summary>
@@ -96,9 +121,9 @@ namespace YooAsset
public IDeliveryQueryServices DeliveryQueryServices = null;
/// <summary>
/// 远端资源地址查询服务类
/// 分发资源加载服务接口
/// </summary>
public IRemoteServices RemoteServices = null;
public IDeliveryLoadServices DeliveryLoadServices = null;
}
/// <summary>
@@ -106,14 +131,14 @@ namespace YooAsset
/// </summary>
public class WebPlayModeParameters : InitializeParameters
{
/// <summary>
/// 内置资源查询服务接口
/// </summary>
public IBuildinQueryServices BuildinQueryServices = null;
/// <summary>
/// 远端资源地址查询服务类
/// </summary>
public IRemoteServices RemoteServices = null;
/// <summary>
/// 内置资源查询服务接口
/// </summary>
public IBuildinQueryServices BuildinQueryServices = null;
}
}
@@ -10,6 +10,11 @@ namespace YooAsset
// 用户请求的回调
private Action<AsyncOperationBase> _callback;
/// <summary>
/// 所属包裹
/// </summary>
public string PackageName { private set; get; }
/// <summary>
/// 状态
/// </summary>
@@ -74,6 +79,20 @@ namespace YooAsset
internal abstract void Start();
internal abstract void Update();
internal void SetPackageName(string packageName)
{
PackageName = packageName;
}
internal void SetAbort()
{
if (IsDone == false)
{
Status = EOperationStatus.Failed;
Error = "user abort";
YooLogger.Warning($"Async operaiton has been abort : {this.GetType().Name}");
SetFinish();
}
}
internal void SetFinish()
{
Progress = 1f;
@@ -6,9 +6,9 @@ namespace YooAsset
{
internal class OperationSystem
{
private static readonly List<AsyncOperationBase> _operations = new List<AsyncOperationBase>(100);
private static readonly List<AsyncOperationBase> _addList = new List<AsyncOperationBase>(100);
private static readonly List<AsyncOperationBase> _removeList = new List<AsyncOperationBase>(100);
private static readonly List<AsyncOperationBase> _operations = new List<AsyncOperationBase>(1000);
private static readonly List<AsyncOperationBase> _addList = new List<AsyncOperationBase>(1000);
private static readonly List<AsyncOperationBase> _removeList = new List<AsyncOperationBase>(1000);
// 计时器相关
private static Stopwatch _watch;
@@ -58,11 +58,12 @@ namespace YooAsset
}
// 更新所有的异步操作
foreach (var operation in _operations)
for (int i = 0; i < _operations.Count; i++)
{
if (IsBusy)
break;
var operation = _operations[i];
operation.Update();
if (operation.IsDone)
{
@@ -95,12 +96,41 @@ namespace YooAsset
MaxTimeSlice = long.MaxValue;
}
/// <summary>
/// 销毁包裹的所有任务
/// </summary>
public static void ClearPackageOperation(string packageName)
{
// 移除临时队列里的任务
for (int i = _addList.Count - 1; i >= 0; i--)
{
var operation = _addList[i];
if (operation.PackageName == packageName)
{
operation.SetAbort();
_addList.RemoveAt(i);
}
}
// 移除正在进行的任务
for (int i = _operations.Count - 1; i >= 0; i--)
{
var operation = _operations[i];
if (operation.PackageName == packageName)
{
operation.SetAbort();
_operations.RemoveAt(i);
}
}
}
/// <summary>
/// 开始处理异步操作类
/// </summary>
public static void StartOperation(AsyncOperationBase operation)
public static void StartOperation(string packageName, AsyncOperationBase operation)
{
_addList.Add(operation);
operation.SetPackageName(packageName);
operation.SetStart();
operation.Start();
}
@@ -1,84 +0,0 @@
namespace YooAsset
{
internal class BundleInfo
{
public enum ELoadMode
{
None,
LoadFromDelivery,
LoadFromStreaming,
LoadFromCache,
LoadFromRemote,
LoadFromEditor,
}
public readonly PackageBundle Bundle;
public readonly ELoadMode LoadMode;
/// <summary>
/// 远端下载地址
/// </summary>
public string RemoteMainURL { private set; get; }
/// <summary>
/// 远端下载备用地址
/// </summary>
public string RemoteFallbackURL { private set; get; }
/// <summary>
/// 开发者分发的文件地址
/// </summary>
public string DeliveryFilePath { private set; get; }
/// <summary>
/// 开发者分发的文件偏移量
/// </summary>
public ulong DeliveryFileOffset { private set; get; }
/// <summary>
/// 注意:该字段只用于帮助编辑器下的模拟模式。
/// </summary>
public string[] IncludeAssets;
private BundleInfo()
{
}
public BundleInfo(PackageBundle bundle, ELoadMode loadMode, string mainURL, string fallbackURL)
{
Bundle = bundle;
LoadMode = loadMode;
RemoteMainURL = mainURL;
RemoteFallbackURL = fallbackURL;
DeliveryFilePath = string.Empty;
DeliveryFileOffset = 0;
}
public BundleInfo(PackageBundle bundle, ELoadMode loadMode, string deliveryFilePath, ulong deliveryFileOffset)
{
Bundle = bundle;
LoadMode = loadMode;
RemoteMainURL = string.Empty;
RemoteFallbackURL = string.Empty;
DeliveryFilePath = deliveryFilePath;
DeliveryFileOffset = deliveryFileOffset;
}
public BundleInfo(PackageBundle bundle, ELoadMode loadMode)
{
Bundle = bundle;
LoadMode = loadMode;
RemoteMainURL = string.Empty;
RemoteFallbackURL = string.Empty;
DeliveryFilePath = string.Empty;
DeliveryFileOffset = 0;
}
/// <summary>
/// 是否为JAR包内文件
/// </summary>
public static bool IsBuildinJarFile(string streamingPath)
{
return streamingPath.StartsWith("jar:");
}
}
}
@@ -1,237 +0,0 @@
using System;
using System.Linq;
namespace YooAsset
{
[Serializable]
internal class PackageBundle
{
/// <summary>
/// 资源包名称
/// </summary>
public string BundleName;
/// <summary>
/// Unity引擎生成的CRC
/// </summary>
public uint UnityCRC;
/// <summary>
/// 文件哈希值
/// </summary>
public string FileHash;
/// <summary>
/// 文件校验码
/// </summary>
public string FileCRC;
/// <summary>
/// 文件大小(字节数)
/// </summary>
public long FileSize;
/// <summary>
/// 是否为原生文件
/// </summary>
public bool IsRawFile;
/// <summary>
/// 加载方法
/// </summary>
public byte LoadMethod;
/// <summary>
/// 资源包的分类标签
/// </summary>
public string[] Tags;
/// <summary>
/// 引用该资源包的ID列表
/// </summary>
public int[] ReferenceIDs;
/// <summary>
/// 所属的包裹名称
/// </summary>
public string PackageName { private set; get; }
/// <summary>
/// 缓存GUID
/// </summary>
public string CacheGUID
{
get { return FileHash; }
}
/// <summary>
/// 缓存的数据文件路径
/// </summary>
private string _cachedDataFilePath;
public string CachedDataFilePath
{
get
{
if (string.IsNullOrEmpty(_cachedDataFilePath) == false)
return _cachedDataFilePath;
string folderName = FileHash.Substring(0, 2);
if (IsRawFile)
{
string cacheRoot = PersistentTools.GetPersistent(PackageName).SandboxCacheRawFilesRoot;
_cachedDataFilePath = PathUtility.Combine(cacheRoot, folderName, CacheGUID, YooAssetSettings.CacheBundleDataFileName);
_cachedDataFilePath += _fileExtension;
}
else
{
string cacheRoot = PersistentTools.GetPersistent(PackageName).SandboxCacheBundleFilesRoot;
_cachedDataFilePath = PathUtility.Combine(cacheRoot, folderName, CacheGUID, YooAssetSettings.CacheBundleDataFileName);
}
return _cachedDataFilePath;
}
}
/// <summary>
/// 缓存的信息文件路径
/// </summary>
private string _cachedInfoFilePath;
public string CachedInfoFilePath
{
get
{
if (string.IsNullOrEmpty(_cachedInfoFilePath) == false)
return _cachedInfoFilePath;
string folderName = FileHash.Substring(0, 2);
if (IsRawFile)
{
string cacheRoot = PersistentTools.GetPersistent(PackageName).SandboxCacheRawFilesRoot;
_cachedInfoFilePath = PathUtility.Combine(cacheRoot, folderName, CacheGUID, YooAssetSettings.CacheBundleInfoFileName);
}
else
{
string cacheRoot = PersistentTools.GetPersistent(PackageName).SandboxCacheBundleFilesRoot;
_cachedInfoFilePath = PathUtility.Combine(cacheRoot, folderName, CacheGUID, YooAssetSettings.CacheBundleInfoFileName);
}
return _cachedInfoFilePath;
}
}
/// <summary>
/// 临时的数据文件路径
/// </summary>
private string _tempDataFilePath;
public string TempDataFilePath
{
get
{
if (string.IsNullOrEmpty(_tempDataFilePath) == false)
return _tempDataFilePath;
_tempDataFilePath = $"{CachedDataFilePath}.temp";
return _tempDataFilePath;
}
}
/// <summary>
/// 内置文件路径
/// </summary>
private string _streamingFilePath;
public string StreamingFilePath
{
get
{
if (string.IsNullOrEmpty(_streamingFilePath) == false)
return _streamingFilePath;
string root = PersistentTools.GetPersistent(PackageName).BuildinPackageRoot;
_streamingFilePath = PathUtility.Combine(root, FileName);
return _streamingFilePath;
}
}
/// <summary>
/// 文件名称
/// </summary>
private string _fileName;
public string FileName
{
get
{
if (string.IsNullOrEmpty(_fileName))
throw new Exception("Should never get here !");
return _fileName;
}
}
/// <summary>
/// 文件后缀名
/// </summary>
private string _fileExtension;
public string FileExtension
{
get
{
if (string.IsNullOrEmpty(_fileExtension))
throw new Exception("Should never get here !");
return _fileExtension;
}
}
public PackageBundle()
{
}
/// <summary>
/// 解析资源包
/// </summary>
public void ParseBundle(string packageName, int nameStype)
{
PackageName = packageName;
_fileExtension = ManifestTools.GetRemoteBundleFileExtension(BundleName);
_fileName = ManifestTools.GetRemoteBundleFileName(nameStype, BundleName, _fileExtension, FileHash);
}
/// <summary>
/// 是否包含Tag
/// </summary>
public bool HasTag(string[] tags)
{
if (tags == null || tags.Length == 0)
return false;
if (Tags == null || Tags.Length == 0)
return false;
foreach (var tag in tags)
{
if (Tags.Contains(tag))
return true;
}
return false;
}
/// <summary>
/// 是否包含任意Tags
/// </summary>
public bool HasAnyTags()
{
if (Tags != null && Tags.Length > 0)
return true;
else
return false;
}
/// <summary>
/// 检测资源包文件内容是否相同
/// </summary>
public bool Equals(PackageBundle otherBundle)
{
if (FileHash == otherBundle.FileHash)
return true;
return false;
}
}
}
@@ -1,123 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset
{
internal class EditorSimulateModeImpl : IPlayModeServices, IBundleServices
{
private PackageManifest _activeManifest;
/// <summary>
/// 异步初始化
/// </summary>
public InitializationOperation InitializeAsync(string simulateManifestFilePath)
{
var operation = new EditorSimulateModeInitializationOperation(this, simulateManifestFilePath);
OperationSystem.StartOperation(operation);
return operation;
}
#region IPlayModeServices接口
public PackageManifest ActiveManifest
{
set
{
_activeManifest = value;
}
get
{
return _activeManifest;
}
}
public void FlushManifestVersionFile()
{
}
UpdatePackageVersionOperation IPlayModeServices.UpdatePackageVersionAsync(bool appendTimeTicks, int timeout)
{
var operation = new EditorPlayModeUpdatePackageVersionOperation();
OperationSystem.StartOperation(operation);
return operation;
}
UpdatePackageManifestOperation IPlayModeServices.UpdatePackageManifestAsync(string packageVersion, bool autoSaveVersion, int timeout)
{
var operation = new EditorPlayModeUpdatePackageManifestOperation();
OperationSystem.StartOperation(operation);
return operation;
}
PreDownloadContentOperation IPlayModeServices.PreDownloadContentAsync(string packageVersion, int timeout)
{
var operation = new EditorPlayModePreDownloadContentOperation();
OperationSystem.StartOperation(operation);
return operation;
}
ResourceDownloaderOperation IPlayModeServices.CreateResourceDownloaderByAll(int downloadingMaxNumber, int failedTryAgain, int timeout)
{
return ResourceDownloaderOperation.CreateEmptyDownloader(downloadingMaxNumber, failedTryAgain, timeout);
}
ResourceDownloaderOperation IPlayModeServices.CreateResourceDownloaderByTags(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout)
{
return ResourceDownloaderOperation.CreateEmptyDownloader(downloadingMaxNumber, failedTryAgain, timeout);
}
ResourceDownloaderOperation IPlayModeServices.CreateResourceDownloaderByPaths(AssetInfo[] assetInfos, int downloadingMaxNumber, int failedTryAgain, int timeout)
{
return ResourceDownloaderOperation.CreateEmptyDownloader(downloadingMaxNumber, failedTryAgain, timeout);
}
ResourceUnpackerOperation IPlayModeServices.CreateResourceUnpackerByAll(int upackingMaxNumber, int failedTryAgain, int timeout)
{
return ResourceUnpackerOperation.CreateEmptyUnpacker(upackingMaxNumber, failedTryAgain, timeout);
}
ResourceUnpackerOperation IPlayModeServices.CreateResourceUnpackerByTags(string[] tags, int upackingMaxNumber, int failedTryAgain, int timeout)
{
return ResourceUnpackerOperation.CreateEmptyUnpacker(upackingMaxNumber, failedTryAgain, timeout);
}
#endregion
#region IBundleServices接口
private BundleInfo CreateBundleInfo(PackageBundle packageBundle, AssetInfo assetInfo)
{
if (packageBundle == null)
throw new Exception("Should never get here !");
BundleInfo bundleInfo = new BundleInfo(packageBundle, BundleInfo.ELoadMode.LoadFromEditor);
bundleInfo.IncludeAssets = _activeManifest.GetBundleIncludeAssets(assetInfo.AssetPath);
return bundleInfo;
}
BundleInfo IBundleServices.GetBundleInfo(AssetInfo assetInfo)
{
if (assetInfo.IsInvalid)
throw new Exception("Should never get here !");
// 注意:如果清单里未找到资源包会抛出异常!
var packageBundle = _activeManifest.GetMainPackageBundle(assetInfo.AssetPath);
return CreateBundleInfo(packageBundle, assetInfo);
}
BundleInfo[] IBundleServices.GetAllDependBundleInfos(AssetInfo assetInfo)
{
if (assetInfo.IsInvalid)
throw new Exception("Should never get here !");
// 注意:如果清单里未找到资源包会抛出异常!
var depends = _activeManifest.GetAllDependencies(assetInfo.AssetPath);
List<BundleInfo> result = new List<BundleInfo>(depends.Length);
foreach (var packageBundle in depends)
{
BundleInfo bundleInfo = CreateBundleInfo(packageBundle, assetInfo);
result.Add(bundleInfo);
}
return result.ToArray();
}
string IBundleServices.GetBundleName(int bundleID)
{
return _activeManifest.GetBundleName(bundleID);
}
bool IBundleServices.IsServicesValid()
{
return _activeManifest != null;
}
#endregion
}
}
@@ -1,158 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset
{
internal class WebPlayModeImpl : IPlayModeServices, IBundleServices
{
private PackageManifest _activeManifest;
// 参数相关
private string _packageName;
private IBuildinQueryServices _buildinQueryServices;
private IRemoteServices _remoteServices;
public IRemoteServices RemoteServices
{
get { return _remoteServices; }
}
/// <summary>
/// 异步初始化
/// </summary>
public InitializationOperation InitializeAsync(string packageName, IBuildinQueryServices buildinQueryServices, IRemoteServices remoteServices)
{
_packageName = packageName;
_buildinQueryServices = buildinQueryServices;
_remoteServices = remoteServices;
var operation = new WebPlayModeInitializationOperation(this, packageName);
OperationSystem.StartOperation(operation);
return operation;
}
// 下载相关
private BundleInfo ConvertToDownloadInfo(PackageBundle packageBundle)
{
string remoteMainURL = _remoteServices.GetRemoteMainURL(packageBundle.FileName);
string remoteFallbackURL = _remoteServices.GetRemoteFallbackURL(packageBundle.FileName);
BundleInfo bundleInfo = new BundleInfo(packageBundle, BundleInfo.ELoadMode.LoadFromRemote, remoteMainURL, remoteFallbackURL);
return bundleInfo;
}
// 查询相关
private bool IsBuildinPackageBundle(PackageBundle packageBundle)
{
return _buildinQueryServices.QueryStreamingAssets(_packageName, packageBundle.FileName);
}
#region IPlayModeServices接口
public PackageManifest ActiveManifest
{
set
{
_activeManifest = value;
}
get
{
return _activeManifest;
}
}
public void FlushManifestVersionFile()
{
}
UpdatePackageVersionOperation IPlayModeServices.UpdatePackageVersionAsync(bool appendTimeTicks, int timeout)
{
var operation = new WebPlayModeUpdatePackageVersionOperation(this, _packageName, appendTimeTicks, timeout);
OperationSystem.StartOperation(operation);
return operation;
}
UpdatePackageManifestOperation IPlayModeServices.UpdatePackageManifestAsync(string packageVersion, bool autoSaveVersion, int timeout)
{
var operation = new WebPlayModeUpdatePackageManifestOperation(this, _packageName, packageVersion, timeout);
OperationSystem.StartOperation(operation);
return operation;
}
PreDownloadContentOperation IPlayModeServices.PreDownloadContentAsync(string packageVersion, int timeout)
{
var operation = new WebPlayModePreDownloadContentOperation();
OperationSystem.StartOperation(operation);
return operation;
}
ResourceDownloaderOperation IPlayModeServices.CreateResourceDownloaderByAll(int downloadingMaxNumber, int failedTryAgain, int timeout)
{
return ResourceDownloaderOperation.CreateEmptyDownloader(downloadingMaxNumber, failedTryAgain, timeout);
}
ResourceDownloaderOperation IPlayModeServices.CreateResourceDownloaderByTags(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout)
{
return ResourceDownloaderOperation.CreateEmptyDownloader(downloadingMaxNumber, failedTryAgain, timeout);
}
ResourceDownloaderOperation IPlayModeServices.CreateResourceDownloaderByPaths(AssetInfo[] assetInfos, int downloadingMaxNumber, int failedTryAgain, int timeout)
{
return ResourceDownloaderOperation.CreateEmptyDownloader(downloadingMaxNumber, failedTryAgain, timeout);
}
ResourceUnpackerOperation IPlayModeServices.CreateResourceUnpackerByAll(int upackingMaxNumber, int failedTryAgain, int timeout)
{
return ResourceUnpackerOperation.CreateEmptyUnpacker(upackingMaxNumber, failedTryAgain, timeout);
}
ResourceUnpackerOperation IPlayModeServices.CreateResourceUnpackerByTags(string[] tags, int upackingMaxNumber, int failedTryAgain, int timeout)
{
return ResourceUnpackerOperation.CreateEmptyUnpacker(upackingMaxNumber, failedTryAgain, timeout);
}
#endregion
#region IBundleServices接口
private BundleInfo CreateBundleInfo(PackageBundle packageBundle)
{
if (packageBundle == null)
throw new Exception("Should never get here !");
// 查询APP资源
if (IsBuildinPackageBundle(packageBundle))
{
BundleInfo bundleInfo = new BundleInfo(packageBundle, BundleInfo.ELoadMode.LoadFromStreaming);
return bundleInfo;
}
// 从服务端下载
return ConvertToDownloadInfo(packageBundle);
}
BundleInfo IBundleServices.GetBundleInfo(AssetInfo assetInfo)
{
if (assetInfo.IsInvalid)
throw new Exception("Should never get here !");
// 注意:如果清单里未找到资源包会抛出异常!
var packageBundle = _activeManifest.GetMainPackageBundle(assetInfo.AssetPath);
return CreateBundleInfo(packageBundle);
}
BundleInfo[] IBundleServices.GetAllDependBundleInfos(AssetInfo assetInfo)
{
if (assetInfo.IsInvalid)
throw new Exception("Should never get here !");
// 注意:如果清单里未找到资源包会抛出异常!
var depends = _activeManifest.GetAllDependencies(assetInfo.AssetPath);
List<BundleInfo> result = new List<BundleInfo>(depends.Length);
foreach (var packageBundle in depends)
{
BundleInfo bundleInfo = CreateBundleInfo(packageBundle);
result.Add(bundleInfo);
}
return result.ToArray();
}
string IBundleServices.GetBundleName(int bundleID)
{
return _activeManifest.GetBundleName(bundleID);
}
bool IBundleServices.IsServicesValid()
{
return _activeManifest != null;
}
#endregion
}
}
@@ -3,11 +3,11 @@ using System.Collections.Generic;
namespace YooAsset
{
public sealed class AllAssetsOperationHandle : OperationHandleBase, IDisposable
public sealed class AllAssetsHandle : HandleBase, IDisposable
{
private System.Action<AllAssetsOperationHandle> _callback;
private System.Action<AllAssetsHandle> _callback;
internal AllAssetsOperationHandle(ProviderBase provider) : base(provider)
internal AllAssetsHandle(ProviderBase provider) : base(provider)
{
}
internal override void InvokeCallback()
@@ -18,12 +18,12 @@ namespace YooAsset
/// <summary>
/// 完成委托
/// </summary>
public event System.Action<AllAssetsOperationHandle> Completed
public event System.Action<AllAssetsHandle> Completed
{
add
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(AllAssetsOperationHandle)} is invalid");
throw new System.Exception($"{nameof(AllAssetsHandle)} is invalid");
if (Provider.IsDone)
value.Invoke(this);
else
@@ -32,7 +32,7 @@ namespace YooAsset
remove
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(AllAssetsOperationHandle)} is invalid");
throw new System.Exception($"{nameof(AllAssetsHandle)} is invalid");
_callback -= value;
}
}
@@ -4,11 +4,11 @@ using UnityEngine;
namespace YooAsset
{
public sealed class AssetOperationHandle : OperationHandleBase, IDisposable
public sealed class AssetHandle : HandleBase, IDisposable
{
private System.Action<AssetOperationHandle> _callback;
private System.Action<AssetHandle> _callback;
internal AssetOperationHandle(ProviderBase provider) : base(provider)
internal AssetHandle(ProviderBase provider) : base(provider)
{
}
internal override void InvokeCallback()
@@ -19,12 +19,12 @@ namespace YooAsset
/// <summary>
/// 完成委托
/// </summary>
public event System.Action<AssetOperationHandle> Completed
public event System.Action<AssetHandle> Completed
{
add
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(AssetOperationHandle)} is invalid");
throw new System.Exception($"{nameof(AssetHandle)} is invalid");
if (Provider.IsDone)
value.Invoke(this);
else
@@ -33,7 +33,7 @@ namespace YooAsset
remove
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(AssetOperationHandle)} is invalid");
throw new System.Exception($"{nameof(AssetHandle)} is invalid");
_callback -= value;
}
}
@@ -148,8 +148,9 @@ namespace YooAsset
}
private InstantiateOperation InstantiateAsyncInternal(bool setPositionAndRotation, Vector3 position, Quaternion rotation, Transform parent, bool worldPositionStays)
{
string packageName = GetAssetInfo().PackageName;
InstantiateOperation operation = new InstantiateOperation(this, setPositionAndRotation, position, rotation, parent, worldPositionStays);
OperationSystem.StartOperation(operation);
OperationSystem.StartOperation(packageName, operation);
return operation;
}
}
@@ -3,12 +3,12 @@ using System.Collections;
namespace YooAsset
{
public abstract class OperationHandleBase : IEnumerator
public abstract class HandleBase : IEnumerator
{
private readonly AssetInfo _assetInfo;
internal ProviderBase Provider { private set; get; }
internal OperationHandleBase(ProviderBase provider)
internal HandleBase(ProviderBase provider)
{
Provider = provider;
_assetInfo = provider.MainAssetInfo;
@@ -26,13 +26,13 @@ namespace YooAsset
/// <summary>
/// 获取下载报告
/// </summary>
public DownloadReport GetDownloadReport()
public DownloadStatus GetDownloadStatus()
{
if (IsValidWithWarning == false)
{
return DownloadReport.CreateDefaultReport();
return DownloadStatus.CreateDefaultStatus();
}
return Provider.GetDownloadReport();
return Provider.GetDownloadStatus();
}
/// <summary>
@@ -4,11 +4,11 @@ using System.Text;
namespace YooAsset
{
public class RawFileOperationHandle : OperationHandleBase, IDisposable
public class RawFileHandle : HandleBase, IDisposable
{
private System.Action<RawFileOperationHandle> _callback;
private System.Action<RawFileHandle> _callback;
internal RawFileOperationHandle(ProviderBase provider) : base(provider)
internal RawFileHandle(ProviderBase provider) : base(provider)
{
}
internal override void InvokeCallback()
@@ -19,12 +19,12 @@ namespace YooAsset
/// <summary>
/// 完成委托
/// </summary>
public event System.Action<RawFileOperationHandle> Completed
public event System.Action<RawFileHandle> Completed
{
add
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(RawFileOperationHandle)} is invalid");
throw new System.Exception($"{nameof(RawFileHandle)} is invalid");
if (Provider.IsDone)
value.Invoke(this);
else
@@ -33,7 +33,7 @@ namespace YooAsset
remove
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(RawFileOperationHandle)} is invalid");
throw new System.Exception($"{nameof(RawFileHandle)} is invalid");
_callback -= value;
}
}
@@ -2,12 +2,12 @@
namespace YooAsset
{
public class SceneOperationHandle : OperationHandleBase
public class SceneHandle : HandleBase
{
private System.Action<SceneOperationHandle> _callback;
private System.Action<SceneHandle> _callback;
internal string PackageName { set; get; }
internal SceneOperationHandle(ProviderBase provider) : base(provider)
internal SceneHandle(ProviderBase provider) : base(provider)
{
}
internal override void InvokeCallback()
@@ -18,12 +18,12 @@ namespace YooAsset
/// <summary>
/// 完成委托
/// </summary>
public event System.Action<SceneOperationHandle> Completed
public event System.Action<SceneHandle> Completed
{
add
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(SceneOperationHandle)} is invalid");
throw new System.Exception($"{nameof(SceneHandle)} is invalid");
if (Provider.IsDone)
value.Invoke(this);
else
@@ -32,7 +32,7 @@ namespace YooAsset
remove
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(SceneOperationHandle)} is invalid");
throw new System.Exception($"{nameof(SceneHandle)} is invalid");
_callback -= value;
}
}
@@ -130,12 +130,14 @@ namespace YooAsset
/// </summary>
public UnloadSceneOperation UnloadAsync()
{
string packageName = GetAssetInfo().PackageName;
// 如果句柄无效
if (IsValidWithWarning == false)
{
string error = $"{nameof(SceneOperationHandle)} is invalid.";
string error = $"{nameof(SceneHandle)} is invalid.";
var operation = new UnloadSceneOperation(error);
OperationSystem.StartOperation(operation);
OperationSystem.StartOperation(packageName, operation);
return operation;
}
@@ -145,7 +147,7 @@ namespace YooAsset
string error = $"Cannot unload main scene. Use {nameof(YooAssets.LoadSceneAsync)} method to change the main scene !";
YooLogger.Error(error);
var operation = new UnloadSceneOperation(error);
OperationSystem.StartOperation(operation);
OperationSystem.StartOperation(packageName, operation);
return operation;
}
@@ -154,7 +156,7 @@ namespace YooAsset
Provider.Impl.UnloadSubScene(Provider);
{
var operation = new UnloadSceneOperation(sceneObject);
OperationSystem.StartOperation(operation);
OperationSystem.StartOperation(packageName, operation);
return operation;
}
}
@@ -3,11 +3,11 @@ using System.Collections.Generic;
namespace YooAsset
{
public sealed class SubAssetsOperationHandle : OperationHandleBase, IDisposable
public sealed class SubAssetsHandle : HandleBase, IDisposable
{
private System.Action<SubAssetsOperationHandle> _callback;
private System.Action<SubAssetsHandle> _callback;
internal SubAssetsOperationHandle(ProviderBase provider) : base(provider)
internal SubAssetsHandle(ProviderBase provider) : base(provider)
{
}
internal override void InvokeCallback()
@@ -18,12 +18,12 @@ namespace YooAsset
/// <summary>
/// 完成委托
/// </summary>
public event System.Action<SubAssetsOperationHandle> Completed
public event System.Action<SubAssetsHandle> Completed
{
add
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(SubAssetsOperationHandle)} is invalid");
throw new System.Exception($"{nameof(SubAssetsHandle)} is invalid");
if (Provider.IsDone)
value.Invoke(this);
else
@@ -32,7 +32,7 @@ namespace YooAsset
remove
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(SubAssetsOperationHandle)} is invalid");
throw new System.Exception($"{nameof(SubAssetsHandle)} is invalid");
_callback -= value;
}
}
@@ -27,10 +27,10 @@ namespace YooAsset
private DownloaderBase _unpacker;
private DownloaderBase _downloader;
private AssetBundleCreateRequest _createRequest;
private Stream _stream;
private Stream _managedStream;
public AssetBundleFileLoader(AssetSystemImpl impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
public AssetBundleFileLoader(ResourceManager impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
{
}
@@ -47,31 +47,30 @@ namespace YooAsset
if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
{
_steps = ESteps.Download;
FileLoadPath = MainBundleInfo.Bundle.CachedDataFilePath;
FileLoadPath = MainBundleInfo.CachedDataFilePath;
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{
#if UNITY_ANDROID
EBundleLoadMethod loadMethod = (EBundleLoadMethod)MainBundleInfo.Bundle.LoadMethod;
if (loadMethod == EBundleLoadMethod.LoadFromMemory || loadMethod == EBundleLoadMethod.LoadFromStream)
if (MainBundleInfo.Bundle.Encrypted)
{
_steps = ESteps.Unpack;
FileLoadPath = MainBundleInfo.Bundle.CachedDataFilePath;
FileLoadPath = MainBundleInfo.CachedDataFilePath;
}
else
{
_steps = ESteps.LoadBundleFile;
FileLoadPath = MainBundleInfo.Bundle.StreamingFilePath;
FileLoadPath = MainBundleInfo.BuildinFilePath;
}
#else
_steps = ESteps.LoadBundleFile;
FileLoadPath = MainBundleInfo.Bundle.StreamingFilePath;
FileLoadPath = MainBundleInfo.BuildinFilePath;
#endif
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{
_steps = ESteps.LoadBundleFile;
FileLoadPath = MainBundleInfo.Bundle.CachedDataFilePath;
FileLoadPath = MainBundleInfo.CachedDataFilePath;
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromDelivery)
{
@@ -87,8 +86,7 @@ namespace YooAsset
// 1. 从服务器下载
if (_steps == ESteps.Download)
{
int failedTryAgain = Impl.DownloadFailedTryAgain;
_downloader = DownloadSystem.CreateDownload(MainBundleInfo, failedTryAgain);
_downloader = MainBundleInfo.CreateDownloader(int.MaxValue);
_downloader.SendRequest();
_steps = ESteps.CheckDownload;
}
@@ -117,9 +115,8 @@ namespace YooAsset
// 3. 内置文件解压
if (_steps == ESteps.Unpack)
{
int failedTryAgain = Impl.DownloadFailedTryAgain;
var bundleInfo = ManifestTools.ConvertToUnpackInfo(MainBundleInfo.Bundle);
_unpacker = DownloadSystem.CreateDownload(bundleInfo, failedTryAgain);
int failedTryAgain = 1;
_unpacker = MainBundleInfo.CreateUnpacker(failedTryAgain);
_unpacker.SendRequest();
_steps = ESteps.CheckUnpack;
}
@@ -163,60 +160,13 @@ namespace YooAsset
DownloadProgress = 1f;
DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize;
// Load assetBundle file
var loadMethod = (EBundleLoadMethod)MainBundleInfo.Bundle.LoadMethod;
if (loadMethod == EBundleLoadMethod.Normal)
{
if (_isWaitForAsyncComplete)
CacheBundle = AssetBundle.LoadFromFile(FileLoadPath);
else
_createRequest = AssetBundle.LoadFromFileAsync(FileLoadPath);
}
// 加载AssetBundle资源对象
// 注意:解密服务类可能会返回空的对象。
if (_isWaitForAsyncComplete)
CacheBundle = MainBundleInfo.LoadAssetBundle(FileLoadPath, out _managedStream);
else
{
if (Impl.DecryptionServices == null)
{
_steps = ESteps.Done;
Status = EStatus.Failed;
LastError = $"{nameof(IDecryptionServices)} is null : {MainBundleInfo.Bundle.BundleName}";
YooLogger.Error(LastError);
return;
}
_createRequest = MainBundleInfo.LoadAssetBundleAsync(FileLoadPath, out _managedStream);
DecryptFileInfo fileInfo = new DecryptFileInfo();
fileInfo.BundleName = MainBundleInfo.Bundle.BundleName;
fileInfo.FilePath = FileLoadPath;
if (loadMethod == EBundleLoadMethod.LoadFromFileOffset)
{
ulong offset = Impl.DecryptionServices.LoadFromFileOffset(fileInfo);
if (_isWaitForAsyncComplete)
CacheBundle = AssetBundle.LoadFromFile(FileLoadPath, 0, offset);
else
_createRequest = AssetBundle.LoadFromFileAsync(FileLoadPath, 0, offset);
}
else if (loadMethod == EBundleLoadMethod.LoadFromMemory)
{
byte[] fileData = Impl.DecryptionServices.LoadFromMemory(fileInfo);
if (_isWaitForAsyncComplete)
CacheBundle = AssetBundle.LoadFromMemory(fileData);
else
_createRequest = AssetBundle.LoadFromMemoryAsync(fileData);
}
else if (loadMethod == EBundleLoadMethod.LoadFromStream)
{
_stream = Impl.DecryptionServices.LoadFromStream(fileInfo);
uint managedReadBufferSize = Impl.DecryptionServices.GetManagedReadBufferSize();
if (_isWaitForAsyncComplete)
CacheBundle = AssetBundle.LoadFromStream(_stream, 0, managedReadBufferSize);
else
_createRequest = AssetBundle.LoadFromStreamAsync(_stream, 0, managedReadBufferSize);
}
else
{
throw new System.NotImplementedException();
}
}
_steps = ESteps.CheckLoadFile;
}
@@ -228,23 +178,11 @@ namespace YooAsset
DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize;
// Load assetBundle file
var loadMethod = (EBundleLoadMethod)MainBundleInfo.Bundle.LoadMethod;
if (loadMethod == EBundleLoadMethod.Normal)
{
ulong offset = MainBundleInfo.DeliveryFileOffset;
if (_isWaitForAsyncComplete)
CacheBundle = AssetBundle.LoadFromFile(FileLoadPath, 0, offset);
else
_createRequest = AssetBundle.LoadFromFileAsync(FileLoadPath, 0, offset);
}
if (_isWaitForAsyncComplete)
CacheBundle = MainBundleInfo.LoadDeliveryAssetBundle(FileLoadPath);
else
{
_steps = ESteps.Done;
Status = EStatus.Failed;
LastError = $"Delivery file not support encryption : {MainBundleInfo.Bundle.BundleName}";
YooLogger.Error(LastError);
return;
}
_createRequest = MainBundleInfo.LoadDeliveryAssetBundleAsync(FileLoadPath);
_steps = ESteps.CheckLoadFile;
}
@@ -279,11 +217,11 @@ namespace YooAsset
// 在AssetBundle文件加载失败的情况下,我们需要重新验证文件的完整性!
if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{
var result = CacheSystem.VerifyingRecordFile(MainBundleInfo.Bundle.PackageName, MainBundleInfo.Bundle.CacheGUID);
var result = MainBundleInfo.VerifySelf();
if (result != EVerifyResult.Succeed)
{
YooLogger.Error($"Found possibly corrupt file ! {MainBundleInfo.Bundle.CacheGUID} Verify result : {result}");
CacheSystem.DiscardFile(MainBundleInfo.Bundle.PackageName, MainBundleInfo.Bundle.CacheGUID);
MainBundleInfo.CacheDiscard();
}
}
}
@@ -302,11 +240,11 @@ namespace YooAsset
{
base.Destroy();
if (_stream != null)
if (_managedStream != null)
{
_stream.Close();
_stream.Dispose();
_stream = null;
_managedStream.Close();
_managedStream.Dispose();
_managedStream = null;
}
}
@@ -22,10 +22,10 @@ namespace YooAsset
}
private ESteps _steps = ESteps.None;
private WebDownloader _downloader;
private DownloaderBase _downloader;
public AssetBundleWebLoader(AssetSystemImpl impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
public AssetBundleWebLoader(ResourceManager impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
{
}
@@ -58,8 +58,7 @@ namespace YooAsset
// 1. 跨域获取资源包
if (_steps == ESteps.LoadRemoteFile)
{
int failedTryAgain = Impl.DownloadFailedTryAgain;
_downloader = DownloadSystem.CreateDownload(MainBundleInfo, failedTryAgain) as WebDownloader;
_downloader = MainBundleInfo.CreateDownloader(int.MaxValue);
_downloader.SendRequest(true);
_steps = ESteps.CheckLoadFile;
}
@@ -67,9 +66,7 @@ namespace YooAsset
// 2. 从站点获取资源包
if (_steps == ESteps.LoadWebSiteFile)
{
int failedTryAgain = Impl.DownloadFailedTryAgain;
var bundleInfo = ManifestTools.ConvertToUnpackInfo(MainBundleInfo.Bundle);
_downloader = DownloadSystem.CreateDownload(bundleInfo, failedTryAgain) as WebDownloader;
_downloader = MainBundleInfo.CreateUnpacker(int.MaxValue);
_downloader.SendRequest(true);
_steps = ESteps.CheckLoadFile;
}
@@ -95,9 +92,6 @@ namespace YooAsset
_steps = ESteps.Done;
Status = EStatus.Succeed;
}
// 注意:释放下载句柄
_downloader.DisposeHandler();
}
}
@@ -17,7 +17,7 @@ namespace YooAsset
/// <summary>
/// 所属资源系统
/// </summary>
public AssetSystemImpl Impl { private set; get; }
public ResourceManager Impl { private set; get; }
/// <summary>
/// 资源包文件信息
@@ -51,7 +51,7 @@ namespace YooAsset
internal ulong DownloadedBytes { set; get; }
public BundleLoaderBase(AssetSystemImpl impl, BundleInfo bundleInfo)
public BundleLoaderBase(ResourceManager impl, BundleInfo bundleInfo)
{
Impl = impl;
MainBundleInfo = bundleInfo;
@@ -103,14 +103,6 @@ namespace YooAsset
if (RefCount > 0)
return false;
// 检查引用链上的资源包是否已经全部销毁
// 注意:互相引用的资源包无法卸载!
foreach (var bundleID in MainBundleInfo.Bundle.ReferenceIDs)
{
if (Impl.CheckBundleDestroyed(bundleID) == false)
return false;
}
return true;
}
@@ -20,7 +20,7 @@ namespace YooAsset
private DownloaderBase _downloader;
public RawBundleFileLoader(AssetSystemImpl impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
public RawBundleFileLoader(ResourceManager impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
{
}
@@ -37,22 +37,22 @@ namespace YooAsset
if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
{
_steps = ESteps.Download;
FileLoadPath = MainBundleInfo.Bundle.CachedDataFilePath;
FileLoadPath = MainBundleInfo.CachedDataFilePath;
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{
#if UNITY_ANDROID
_steps = ESteps.Unpack;
FileLoadPath = MainBundleInfo.Bundle.CachedDataFilePath;
FileLoadPath = MainBundleInfo.CachedDataFilePath;
#else
_steps = ESteps.CheckFile;
FileLoadPath = MainBundleInfo.Bundle.StreamingFilePath;
FileLoadPath = MainBundleInfo.BuildinFilePath;
#endif
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{
_steps = ESteps.CheckFile;
FileLoadPath = MainBundleInfo.Bundle.CachedDataFilePath;
FileLoadPath = MainBundleInfo.CachedDataFilePath;
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromDelivery)
{
@@ -68,8 +68,7 @@ namespace YooAsset
// 1. 下载远端文件
if (_steps == ESteps.Download)
{
int failedTryAgain = Impl.DownloadFailedTryAgain;
_downloader = DownloadSystem.CreateDownload(MainBundleInfo, failedTryAgain);
_downloader = MainBundleInfo.CreateDownloader(int.MaxValue);
_downloader.SendRequest();
_steps = ESteps.CheckDownload;
}
@@ -97,9 +96,8 @@ namespace YooAsset
// 3. 解压内置文件
if (_steps == ESteps.Unpack)
{
int failedTryAgain = Impl.DownloadFailedTryAgain;
var bundleInfo = ManifestTools.ConvertToUnpackInfo(MainBundleInfo.Bundle);
_unpacker = DownloadSystem.CreateDownload(bundleInfo, failedTryAgain);
int failedTryAgain = 1;
_unpacker = MainBundleInfo.CreateUnpacker(failedTryAgain);
_unpacker.SendRequest();
_steps = ESteps.CheckUnpack;
}
@@ -23,7 +23,7 @@ namespace YooAsset
private DownloaderBase _downloader;
public RawBundleWebLoader(AssetSystemImpl impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
public RawBundleWebLoader(ResourceManager impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
{
}
@@ -40,12 +40,12 @@ namespace YooAsset
if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
{
_steps = ESteps.Download;
FileLoadPath = MainBundleInfo.Bundle.CachedDataFilePath;
FileLoadPath = MainBundleInfo.CachedDataFilePath;
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromStreaming)
{
_steps = ESteps.Website;
FileLoadPath = MainBundleInfo.Bundle.CachedDataFilePath;
FileLoadPath = MainBundleInfo.CachedDataFilePath;
}
else
{
@@ -56,8 +56,7 @@ namespace YooAsset
// 1. 下载远端文件
if (_steps == ESteps.Download)
{
int failedTryAgain = Impl.DownloadFailedTryAgain;
_downloader = DownloadSystem.CreateDownload(MainBundleInfo, failedTryAgain);
_downloader = MainBundleInfo.CreateDownloader(int.MaxValue);
_downloader.SendRequest();
_steps = ESteps.CheckDownload;
}
@@ -85,9 +84,7 @@ namespace YooAsset
// 3. 从站点下载
if (_steps == ESteps.Website)
{
int failedTryAgain = Impl.DownloadFailedTryAgain;
var bundleInfo = ManifestTools.ConvertToUnpackInfo(MainBundleInfo.Bundle);
_website = DownloadSystem.CreateDownload(bundleInfo, failedTryAgain);
_website = MainBundleInfo.CreateUnpacker(int.MaxValue);
_website.SendRequest();
_steps = ESteps.CheckWebsite;
}
@@ -12,7 +12,7 @@ namespace YooAsset
private ESteps _steps = ESteps.None;
public VirtualBundleFileLoader(AssetSystemImpl impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
public VirtualBundleFileLoader(ResourceManager impl, BundleInfo bundleInfo) : base(impl, bundleInfo)
{
}
@@ -11,7 +11,7 @@ namespace YooAsset
Done,
}
private readonly AssetOperationHandle _handle;
private readonly AssetHandle _handle;
private readonly bool _setPositionAndRotation;
private readonly Vector3 _position;
private readonly Quaternion _rotation;
@@ -25,7 +25,7 @@ namespace YooAsset
public GameObject Result = null;
internal InstantiateOperation(AssetOperationHandle handle, bool setPositionAndRotation, Vector3 position, Quaternion rotation, Transform parent, bool worldPositionStays)
internal InstantiateOperation(AssetHandle handle, bool setPositionAndRotation, Vector3 position, Quaternion rotation, Transform parent, bool worldPositionStays)
{
_handle = handle;
_setPositionAndRotation = setPositionAndRotation;
@@ -49,7 +49,7 @@ namespace YooAsset
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"{nameof(AssetOperationHandle)} is invalid.";
Error = $"{nameof(AssetHandle)} is invalid.";
return;
}
@@ -60,7 +60,7 @@ namespace YooAsset
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"{nameof(AssetOperationHandle.AssetObject)} is null.";
Error = $"{nameof(AssetHandle.AssetObject)} is null.";
return;
}

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