ProviderBase.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Threading.Tasks;
  5. using System;
  6. namespace YooAsset
  7. {
  8. internal abstract class ProviderBase : AsyncOperationBase
  9. {
  10. protected enum ESteps
  11. {
  12. None = 0,
  13. CheckBundle,
  14. Loading,
  15. Checking,
  16. Done,
  17. }
  18. /// <summary>
  19. /// 资源提供者唯一标识符
  20. /// </summary>
  21. public string ProviderGUID { private set; get; }
  22. /// <summary>
  23. /// 所属资源系统
  24. /// </summary>
  25. public ResourceManager ResourceMgr { private set; get; }
  26. /// <summary>
  27. /// 资源信息
  28. /// </summary>
  29. public AssetInfo MainAssetInfo { private set; get; }
  30. /// <summary>
  31. /// 获取的资源对象
  32. /// </summary>
  33. public UnityEngine.Object AssetObject { protected set; get; }
  34. /// <summary>
  35. /// 获取的资源对象集合
  36. /// </summary>
  37. public UnityEngine.Object[] AllAssetObjects { protected set; get; }
  38. /// <summary>
  39. /// 获取的场景对象
  40. /// </summary>
  41. public UnityEngine.SceneManagement.Scene SceneObject { protected set; get; }
  42. /// <summary>
  43. /// 加载的场景名称
  44. /// </summary>
  45. public string SceneName { protected set; get; }
  46. /// <summary>
  47. /// 原生文件路径
  48. /// </summary>
  49. public string RawFilePath { protected set; get; }
  50. /// <summary>
  51. /// 引用计数
  52. /// </summary>
  53. public int RefCount { private set; get; } = 0;
  54. /// <summary>
  55. /// 是否已经销毁
  56. /// </summary>
  57. public bool IsDestroyed { private set; get; } = false;
  58. protected ESteps _steps = ESteps.None;
  59. protected BundleLoaderBase OwnerBundle { private set; get; }
  60. protected DependAssetBundles DependBundles { private set; get; }
  61. protected bool IsWaitForAsyncComplete { private set; get; } = false;
  62. protected bool IsForceDestroyComplete { private set; get; } = false;
  63. private readonly List<HandleBase> _handles = new List<HandleBase>();
  64. public ProviderBase(ResourceManager manager, string providerGUID, AssetInfo assetInfo)
  65. {
  66. ResourceMgr = manager;
  67. ProviderGUID = providerGUID;
  68. MainAssetInfo = assetInfo;
  69. // 创建资源包加载器
  70. if (manager != null)
  71. {
  72. OwnerBundle = manager.CreateOwnerAssetBundleLoader(assetInfo);
  73. OwnerBundle.Reference();
  74. OwnerBundle.AddProvider(this);
  75. var dependList = manager.CreateDependAssetBundleLoaders(assetInfo);
  76. DependBundles = new DependAssetBundles(dependList);
  77. DependBundles.Reference();
  78. }
  79. }
  80. /// <summary>
  81. /// 销毁资源提供者
  82. /// </summary>
  83. public void Destroy()
  84. {
  85. IsDestroyed = true;
  86. // 检测是否为正常销毁
  87. if (IsDone == false)
  88. {
  89. Error = "User abort !";
  90. Status = EOperationStatus.Failed;
  91. }
  92. // 释放资源包加载器
  93. if (OwnerBundle != null)
  94. {
  95. OwnerBundle.Release();
  96. OwnerBundle = null;
  97. }
  98. if (DependBundles != null)
  99. {
  100. DependBundles.Release();
  101. DependBundles = null;
  102. }
  103. }
  104. /// <summary>
  105. /// 是否可以销毁
  106. /// </summary>
  107. public bool CanDestroy()
  108. {
  109. // 注意:在进行资源加载过程时不可以销毁
  110. if (_steps == ESteps.Loading || _steps == ESteps.Checking)
  111. return false;
  112. return RefCount <= 0;
  113. }
  114. /// <summary>
  115. /// 创建资源句柄
  116. /// </summary>
  117. public T CreateHandle<T>() where T : HandleBase
  118. {
  119. // 引用计数增加
  120. RefCount++;
  121. HandleBase handle;
  122. if (typeof(T) == typeof(AssetHandle))
  123. handle = new AssetHandle(this);
  124. else if (typeof(T) == typeof(SceneHandle))
  125. handle = new SceneHandle(this);
  126. else if (typeof(T) == typeof(SubAssetsHandle))
  127. handle = new SubAssetsHandle(this);
  128. else if (typeof(T) == typeof(AllAssetsHandle))
  129. handle = new AllAssetsHandle(this);
  130. else if (typeof(T) == typeof(RawFileHandle))
  131. handle = new RawFileHandle(this);
  132. else
  133. throw new System.NotImplementedException();
  134. _handles.Add(handle);
  135. return handle as T;
  136. }
  137. /// <summary>
  138. /// 释放资源句柄
  139. /// </summary>
  140. public void ReleaseHandle(HandleBase handle)
  141. {
  142. if (RefCount <= 0)
  143. throw new System.Exception("Should never get here !");
  144. if (_handles.Remove(handle) == false)
  145. throw new System.Exception("Should never get here !");
  146. // 引用计数减少
  147. RefCount--;
  148. }
  149. /// <summary>
  150. /// 释放所有资源句柄
  151. /// </summary>
  152. public void ReleaseAllHandles()
  153. {
  154. for (int i = _handles.Count - 1; i >= 0; i--)
  155. {
  156. var handle = _handles[i];
  157. handle.ReleaseInternal();
  158. }
  159. }
  160. /// <summary>
  161. /// 等待异步执行完毕
  162. /// </summary>
  163. public void WaitForAsyncComplete()
  164. {
  165. IsWaitForAsyncComplete = true;
  166. // 注意:主动轮询更新完成同步加载
  167. InternalOnUpdate();
  168. // 验证结果
  169. if (IsDone == false)
  170. {
  171. YooLogger.Warning($"{nameof(WaitForAsyncComplete)} failed to loading : {MainAssetInfo.AssetPath}");
  172. }
  173. }
  174. /// <summary>
  175. /// 强制销毁资源提供者
  176. /// </summary>
  177. public void ForceDestroyComplete()
  178. {
  179. IsForceDestroyComplete = true;
  180. // 注意:主动轮询更新完成同步加载
  181. // 说明:如果资源包未准备完毕也可以放心销毁。
  182. InternalOnUpdate();
  183. }
  184. /// <summary>
  185. /// 处理特殊异常
  186. /// </summary>
  187. protected void ProcessCacheBundleException()
  188. {
  189. if (OwnerBundle.IsDestroyed)
  190. throw new System.Exception("Should never get here !");
  191. string error = $"The bundle {OwnerBundle.MainBundleInfo.Bundle.BundleName} has been destroyed by unity bugs !";
  192. YooLogger.Error(error);
  193. InvokeCompletion(Error, EOperationStatus.Failed);
  194. }
  195. /// <summary>
  196. /// 结束流程
  197. /// </summary>
  198. protected void InvokeCompletion(string error, EOperationStatus status)
  199. {
  200. DebugEndRecording();
  201. _steps = ESteps.Done;
  202. Error = error;
  203. Status = status;
  204. // 注意:创建临时列表是为了防止外部逻辑在回调函数内创建或者释放资源句柄。
  205. // 注意:回调方法如果发生异常,会阻断列表里的后续回调方法!
  206. List<HandleBase> tempers = new List<HandleBase>(_handles);
  207. foreach (var hande in tempers)
  208. {
  209. if (hande.IsValid)
  210. {
  211. hande.InvokeCallback();
  212. }
  213. }
  214. }
  215. #region 调试信息相关
  216. /// <summary>
  217. /// 出生的场景
  218. /// </summary>
  219. public string SpawnScene = string.Empty;
  220. /// <summary>
  221. /// 出生的时间
  222. /// </summary>
  223. public string SpawnTime = string.Empty;
  224. /// <summary>
  225. /// 加载耗时(单位:毫秒)
  226. /// </summary>
  227. public long LoadingTime { protected set; get; }
  228. // 加载耗时统计
  229. private Stopwatch _watch = null;
  230. [Conditional("DEBUG")]
  231. public void InitSpawnDebugInfo()
  232. {
  233. SpawnScene = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; ;
  234. SpawnTime = SpawnTimeToString(UnityEngine.Time.realtimeSinceStartup);
  235. }
  236. private string SpawnTimeToString(float spawnTime)
  237. {
  238. float h = UnityEngine.Mathf.FloorToInt(spawnTime / 3600f);
  239. float m = UnityEngine.Mathf.FloorToInt(spawnTime / 60f - h * 60f);
  240. float s = UnityEngine.Mathf.FloorToInt(spawnTime - m * 60f - h * 3600f);
  241. return h.ToString("00") + ":" + m.ToString("00") + ":" + s.ToString("00");
  242. }
  243. [Conditional("DEBUG")]
  244. protected void DebugBeginRecording()
  245. {
  246. if (_watch == null)
  247. {
  248. _watch = Stopwatch.StartNew();
  249. }
  250. }
  251. [Conditional("DEBUG")]
  252. private void DebugEndRecording()
  253. {
  254. if (_watch != null)
  255. {
  256. LoadingTime = _watch.ElapsedMilliseconds;
  257. _watch = null;
  258. }
  259. }
  260. /// <summary>
  261. /// 获取下载报告
  262. /// </summary>
  263. internal DownloadStatus GetDownloadStatus()
  264. {
  265. DownloadStatus status = new DownloadStatus();
  266. status.TotalBytes = (ulong)OwnerBundle.MainBundleInfo.Bundle.FileSize;
  267. status.DownloadedBytes = OwnerBundle.DownloadedBytes;
  268. foreach (var dependBundle in DependBundles.DependList)
  269. {
  270. status.TotalBytes += (ulong)dependBundle.MainBundleInfo.Bundle.FileSize;
  271. status.DownloadedBytes += dependBundle.DownloadedBytes;
  272. }
  273. if (status.TotalBytes == 0)
  274. throw new System.Exception("Should never get here !");
  275. status.IsDone = status.DownloadedBytes == status.TotalBytes;
  276. status.Progress = (float)status.DownloadedBytes / status.TotalBytes;
  277. return status;
  278. }
  279. /// <summary>
  280. /// 获取资源包的调试信息列表
  281. /// </summary>
  282. internal void GetBundleDebugInfos(List<DebugBundleInfo> output)
  283. {
  284. var bundleInfo = new DebugBundleInfo();
  285. bundleInfo.BundleName = OwnerBundle.MainBundleInfo.Bundle.BundleName;
  286. bundleInfo.RefCount = OwnerBundle.RefCount;
  287. bundleInfo.Status = OwnerBundle.Status.ToString();
  288. output.Add(bundleInfo);
  289. DependBundles.GetBundleDebugInfos(output);
  290. }
  291. #endregion
  292. }
  293. }