ResourcesComponent.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using UnityEngine;
  7. namespace ET
  8. {
  9. [ObjectSystem]
  10. public class ABInfoAwakeSystem: AwakeSystem<ABInfo, string, AssetBundle>
  11. {
  12. public override void Awake(ABInfo self, string abName, AssetBundle a)
  13. {
  14. self.AssetBundle = a;
  15. self.Name = abName;
  16. self.RefCount = 1;
  17. self.AlreadyLoadAssets = false;
  18. }
  19. }
  20. [ObjectSystem]
  21. public class ABInfoDestroySystem: DestroySystem<ABInfo>
  22. {
  23. public override void Destroy(ABInfo self)
  24. {
  25. //Log.Debug($"desdroy assetbundle: {this.Name}");
  26. self.RefCount = 0;
  27. self.Name = "";
  28. self.AlreadyLoadAssets = false;
  29. self.AssetBundle = null;
  30. }
  31. }
  32. public class ABInfo: Entity, IAwake<string, AssetBundle>, IDestroy
  33. {
  34. public string Name { get; set; }
  35. public int RefCount { get; set; }
  36. public AssetBundle AssetBundle;
  37. public bool AlreadyLoadAssets;
  38. public void Destroy(bool unload = true)
  39. {
  40. if (this.AssetBundle != null)
  41. {
  42. this.AssetBundle.Unload(unload);
  43. }
  44. this.Dispose();
  45. }
  46. }
  47. // 用于字符串转换,减少GC
  48. public static class AssetBundleHelper
  49. {
  50. public static async ETTask<AssetBundle> UnityLoadBundleAsync(string path)
  51. {
  52. var tcs = ETTask<AssetBundle>.Create(true);
  53. AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(path);
  54. request.completed += operation => { tcs.SetResult(request.assetBundle); };
  55. return await tcs;
  56. }
  57. public static async ETTask<UnityEngine.Object[]> UnityLoadAssetAsync(AssetBundle assetBundle)
  58. {
  59. var tcs = ETTask<UnityEngine.Object[]>.Create(true);
  60. AssetBundleRequest request = assetBundle.LoadAllAssetsAsync();
  61. request.completed += operation => { tcs.SetResult(request.allAssets); };
  62. return await tcs;
  63. }
  64. public static string IntToString(this int value)
  65. {
  66. string result;
  67. if (ResourcesComponent.Instance.IntToStringDict.TryGetValue(value, out result))
  68. {
  69. return result;
  70. }
  71. result = value.ToString();
  72. ResourcesComponent.Instance.IntToStringDict[value] = result;
  73. return result;
  74. }
  75. public static string StringToAB(this string value)
  76. {
  77. string result;
  78. if (ResourcesComponent.Instance.StringToABDict.TryGetValue(value, out result))
  79. {
  80. return result;
  81. }
  82. result = value + ".unity3d";
  83. ResourcesComponent.Instance.StringToABDict[value] = result;
  84. return result;
  85. }
  86. public static string IntToAB(this int value)
  87. {
  88. return value.IntToString().StringToAB();
  89. }
  90. public static string BundleNameToLower(this string value)
  91. {
  92. string result;
  93. if (ResourcesComponent.Instance.BundleNameToLowerDict.TryGetValue(value, out result))
  94. {
  95. return result;
  96. }
  97. result = value.ToLower();
  98. ResourcesComponent.Instance.BundleNameToLowerDict[value] = result;
  99. return result;
  100. }
  101. }
  102. [ObjectSystem]
  103. public class ResourcesComponentAwakeSystem: AwakeSystem<ResourcesComponent>
  104. {
  105. public override void Awake(ResourcesComponent self)
  106. {
  107. self.Awake();
  108. }
  109. }
  110. public class ResourcesComponent: Entity, IAwake
  111. {
  112. public static ResourcesComponent Instance { get; set; }
  113. private AssetBundleManifest AssetBundleManifestObject { get; set; }
  114. public Dictionary<int, string> IntToStringDict = new Dictionary<int, string>();
  115. public Dictionary<string, string> StringToABDict = new Dictionary<string, string>();
  116. public Dictionary<string, string> BundleNameToLowerDict = new Dictionary<string, string>() { { "StreamingAssets", "StreamingAssets" } };
  117. private readonly Dictionary<string, Dictionary<string, UnityEngine.Object>> resourceCache =
  118. new Dictionary<string, Dictionary<string, UnityEngine.Object>>();
  119. private readonly Dictionary<string, ABInfo> bundles = new Dictionary<string, ABInfo>();
  120. public void Awake()
  121. {
  122. Instance = this;
  123. if (Define.IsAsync)
  124. {
  125. LoadOneBundle("StreamingAssets");
  126. AssetBundleManifestObject = (AssetBundleManifest)GetAsset("StreamingAssets", "AssetBundleManifest");
  127. }
  128. }
  129. public override void Dispose()
  130. {
  131. if (this.IsDisposed)
  132. {
  133. return;
  134. }
  135. base.Dispose();
  136. Instance = null;
  137. foreach (var abInfo in this.bundles)
  138. {
  139. abInfo.Value.Destroy();
  140. }
  141. this.bundles.Clear();
  142. this.resourceCache.Clear();
  143. this.IntToStringDict.Clear();
  144. this.StringToABDict.Clear();
  145. this.BundleNameToLowerDict.Clear();
  146. }
  147. private string[] GetDependencies(string assetBundleName)
  148. {
  149. string[] dependencies = Array.Empty<string>();
  150. if (DependenciesCache.TryGetValue(assetBundleName, out dependencies))
  151. {
  152. return dependencies;
  153. }
  154. if (!Define.IsAsync)
  155. {
  156. if (Define.IsEditor)
  157. {
  158. dependencies = Define.GetAssetBundleDependencies(assetBundleName, true);
  159. }
  160. }
  161. else
  162. {
  163. dependencies = this.AssetBundleManifestObject.GetAllDependencies(assetBundleName);
  164. }
  165. DependenciesCache.Add(assetBundleName, dependencies);
  166. return dependencies;
  167. }
  168. private string[] GetSortedDependencies(string assetBundleName)
  169. {
  170. var info = new Dictionary<string, int>();
  171. var parents = new List<string>();
  172. CollectDependencies(parents, assetBundleName, info);
  173. string[] ss = info.OrderBy(x => x.Value).Select(x => x.Key).ToArray();
  174. return ss;
  175. }
  176. private void CollectDependencies(List<string> parents, string assetBundleName, Dictionary<string, int> info)
  177. {
  178. parents.Add(assetBundleName);
  179. string[] deps = GetDependencies(assetBundleName);
  180. foreach (string parent in parents)
  181. {
  182. if (!info.ContainsKey(parent))
  183. {
  184. info[parent] = 0;
  185. }
  186. info[parent] += deps.Length;
  187. }
  188. foreach (string dep in deps)
  189. {
  190. if (parents.Contains(dep))
  191. {
  192. throw new Exception($"包有循环依赖,请重新标记: {assetBundleName} {dep}");
  193. }
  194. CollectDependencies(parents, dep, info);
  195. }
  196. parents.RemoveAt(parents.Count - 1);
  197. }
  198. // 缓存包依赖,不用每次计算
  199. private readonly Dictionary<string, string[]> DependenciesCache = new Dictionary<string, string[]>();
  200. public bool Contains(string bundleName)
  201. {
  202. return this.bundles.ContainsKey(bundleName);
  203. }
  204. public Dictionary<string, UnityEngine.Object> GetBundleAll(string bundleName)
  205. {
  206. Dictionary<string, UnityEngine.Object> dict;
  207. if (!this.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
  208. {
  209. throw new Exception($"not found asset: {bundleName}");
  210. }
  211. return dict;
  212. }
  213. public UnityEngine.Object GetAsset(string bundleName, string prefab)
  214. {
  215. Dictionary<string, UnityEngine.Object> dict;
  216. if (!this.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
  217. {
  218. throw new Exception($"not found asset: {bundleName} {prefab}");
  219. }
  220. UnityEngine.Object resource = null;
  221. if (!dict.TryGetValue(prefab, out resource))
  222. {
  223. throw new Exception($"not found asset: {bundleName} {prefab}");
  224. }
  225. return resource;
  226. }
  227. // 一帧卸载一个包,避免卡死
  228. public async ETTask UnloadBundleAsync(string assetBundleName, bool unload = true)
  229. {
  230. assetBundleName = assetBundleName.BundleNameToLower();
  231. string[] dependencies = GetSortedDependencies(assetBundleName);
  232. //Log.Debug($"-----------dep unload start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  233. foreach (string dependency in dependencies)
  234. {
  235. CoroutineLock coroutineLock = null;
  236. try
  237. {
  238. coroutineLock = await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, assetBundleName.GetHashCode());
  239. this.UnloadOneBundle(dependency, unload);
  240. await TimerComponent.Instance.WaitFrameAsync();
  241. }
  242. finally
  243. {
  244. coroutineLock?.Dispose();
  245. }
  246. }
  247. //Log.Debug($"-----------dep unload finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  248. }
  249. // 只允许场景设置unload为false
  250. public void UnloadBundle(string assetBundleName, bool unload = true)
  251. {
  252. assetBundleName = assetBundleName.BundleNameToLower();
  253. string[] dependencies = GetSortedDependencies(assetBundleName);
  254. //Log.Debug($"-----------dep unload start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  255. foreach (string dependency in dependencies)
  256. {
  257. this.UnloadOneBundle(dependency, unload);
  258. }
  259. //Log.Debug($"-----------dep unload finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  260. }
  261. private void UnloadOneBundle(string assetBundleName, bool unload = true)
  262. {
  263. assetBundleName = assetBundleName.BundleNameToLower();
  264. ABInfo abInfo;
  265. if (!this.bundles.TryGetValue(assetBundleName, out abInfo))
  266. {
  267. return;
  268. }
  269. //Log.Debug($"---------------unload one bundle {assetBundleName} refcount: {abInfo.RefCount - 1}");
  270. --abInfo.RefCount;
  271. if (abInfo.RefCount > 0)
  272. {
  273. return;
  274. }
  275. //Log.Debug($"---------------truly unload one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  276. this.bundles.Remove(assetBundleName);
  277. this.resourceCache.Remove(assetBundleName);
  278. abInfo.Destroy(unload);
  279. // Log.Debug($"cache count: {this.cacheDictionary.Count}");
  280. }
  281. /// <summary>
  282. /// 同步加载assetbundle
  283. /// </summary>
  284. /// <param name="assetBundleName"></param>
  285. /// <returns></returns>
  286. public void LoadBundle(string assetBundleName)
  287. {
  288. assetBundleName = assetBundleName.ToLower();
  289. string[] dependencies = GetSortedDependencies(assetBundleName);
  290. //Log.Debug($"-----------dep load start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  291. foreach (string dependency in dependencies)
  292. {
  293. if (string.IsNullOrEmpty(dependency))
  294. {
  295. continue;
  296. }
  297. this.LoadOneBundle(dependency);
  298. }
  299. //Log.Debug($"-----------dep load finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  300. }
  301. private void AddResource(string bundleName, string assetName, UnityEngine.Object resource)
  302. {
  303. Dictionary<string, UnityEngine.Object> dict;
  304. if (!this.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
  305. {
  306. dict = new Dictionary<string, UnityEngine.Object>();
  307. this.resourceCache[bundleName] = dict;
  308. }
  309. dict[assetName] = resource;
  310. }
  311. private void LoadOneBundle(string assetBundleName)
  312. {
  313. assetBundleName = assetBundleName.BundleNameToLower();
  314. ABInfo abInfo;
  315. if (this.bundles.TryGetValue(assetBundleName, out abInfo))
  316. {
  317. ++abInfo.RefCount;
  318. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  319. return;
  320. }
  321. if (!Define.IsAsync)
  322. {
  323. if (Define.IsEditor)
  324. {
  325. string[] realPath = null;
  326. realPath = Define.GetAssetPathsFromAssetBundle(assetBundleName);
  327. foreach (string s in realPath)
  328. {
  329. string assetName = Path.GetFileNameWithoutExtension(s);
  330. UnityEngine.Object resource = Define.LoadAssetAtPath(s);
  331. AddResource(assetBundleName, assetName, resource);
  332. }
  333. if (realPath.Length > 0)
  334. {
  335. abInfo = this.AddChild<ABInfo, string, AssetBundle>(assetBundleName, null);
  336. this.bundles[assetBundleName] = abInfo;
  337. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  338. }
  339. else
  340. {
  341. Log.Error($"assets bundle not found: {assetBundleName}");
  342. }
  343. }
  344. return;
  345. }
  346. string p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
  347. AssetBundle assetBundle = null;
  348. if (File.Exists(p))
  349. {
  350. assetBundle = AssetBundle.LoadFromFile(p);
  351. }
  352. else
  353. {
  354. p = Path.Combine(PathHelper.AppResPath, assetBundleName);
  355. assetBundle = AssetBundle.LoadFromFile(p);
  356. }
  357. if (assetBundle == null)
  358. {
  359. // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
  360. Log.Warning($"assets bundle not found: {assetBundleName}");
  361. return;
  362. }
  363. if (!assetBundle.isStreamedSceneAssetBundle)
  364. {
  365. // 异步load资源到内存cache住
  366. var assets = assetBundle.LoadAllAssets();
  367. foreach (UnityEngine.Object asset in assets)
  368. {
  369. AddResource(assetBundleName, asset.name, asset);
  370. }
  371. }
  372. abInfo = this.AddChild<ABInfo, string, AssetBundle>(assetBundleName, assetBundle);
  373. this.bundles[assetBundleName] = abInfo;
  374. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  375. }
  376. /// <summary>
  377. /// 异步加载assetbundle, 加载ab包分两部分,第一部分是从硬盘加载,第二部分加载all assets。两者不能同时并发
  378. /// </summary>
  379. public async ETTask LoadBundleAsync(string assetBundleName)
  380. {
  381. assetBundleName = assetBundleName.BundleNameToLower();
  382. string[] dependencies = GetSortedDependencies(assetBundleName);
  383. //Log.Debug($"-----------dep load async start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  384. using (ListComponent<ABInfo> abInfos = ListComponent<ABInfo>.Create())
  385. {
  386. async ETTask LoadDependency(string dependency, List<ABInfo> abInfosList)
  387. {
  388. CoroutineLock coroutineLock = null;
  389. try
  390. {
  391. coroutineLock = await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, dependency.GetHashCode());
  392. ABInfo abInfo = await this.LoadOneBundleAsync(dependency);
  393. if (abInfo == null || abInfo.RefCount > 1)
  394. {
  395. return;
  396. }
  397. abInfosList.Add(abInfo);
  398. }
  399. finally
  400. {
  401. coroutineLock?.Dispose();
  402. }
  403. }
  404. // LoadFromFileAsync部分可以并发加载
  405. using (ListComponent<ETTask> tasks = ListComponent<ETTask>.Create())
  406. {
  407. foreach (string dependency in dependencies)
  408. {
  409. tasks.Add(LoadDependency(dependency, abInfos));
  410. }
  411. await ETTaskHelper.WaitAll(tasks);
  412. // ab包从硬盘加载完成,可以再并发加载all assets
  413. tasks.Clear();
  414. foreach (ABInfo abInfo in abInfos)
  415. {
  416. tasks.Add(LoadOneBundleAllAssets(abInfo));
  417. }
  418. await ETTaskHelper.WaitAll(tasks);
  419. }
  420. }
  421. }
  422. private async ETTask<ABInfo> LoadOneBundleAsync(string assetBundleName)
  423. {
  424. assetBundleName = assetBundleName.BundleNameToLower();
  425. ABInfo abInfo;
  426. if (this.bundles.TryGetValue(assetBundleName, out abInfo))
  427. {
  428. ++abInfo.RefCount;
  429. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  430. return null;
  431. }
  432. string p = "";
  433. AssetBundle assetBundle = null;
  434. if (!Define.IsAsync)
  435. {
  436. if (Define.IsEditor)
  437. {
  438. string[] realPath = Define.GetAssetPathsFromAssetBundle(assetBundleName);
  439. foreach (string s in realPath)
  440. {
  441. string assetName = Path.GetFileNameWithoutExtension(s);
  442. UnityEngine.Object resource = Define.LoadAssetAtPath(s);
  443. AddResource(assetBundleName, assetName, resource);
  444. }
  445. if (realPath.Length > 0)
  446. {
  447. abInfo = this.AddChild<ABInfo, string, AssetBundle>(assetBundleName, null);
  448. this.bundles[assetBundleName] = abInfo;
  449. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  450. }
  451. else
  452. {
  453. Log.Error("Bundle not exist! BundleName: " + assetBundleName);
  454. }
  455. // 编辑器模式也不能同步加载
  456. await TimerComponent.Instance.WaitAsync(100);
  457. return abInfo;
  458. }
  459. }
  460. p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
  461. if (!File.Exists(p))
  462. {
  463. p = Path.Combine(PathHelper.AppResPath, assetBundleName);
  464. }
  465. Log.Debug("Async load bundle BundleName : " + p);
  466. // if (!File.Exists(p))
  467. // {
  468. // Log.Error("Async load bundle not exist! BundleName : " + p);
  469. // return null;
  470. // }
  471. assetBundle = await AssetBundleHelper.UnityLoadBundleAsync(p);
  472. if (assetBundle == null)
  473. {
  474. // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
  475. Log.Warning($"assets bundle not found: {assetBundleName}");
  476. return null;
  477. }
  478. abInfo = this.AddChild<ABInfo, string, AssetBundle>(assetBundleName, assetBundle);
  479. this.bundles[assetBundleName] = abInfo;
  480. return abInfo;
  481. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  482. }
  483. // 加载ab包中的all assets
  484. private async ETTask LoadOneBundleAllAssets(ABInfo abInfo)
  485. {
  486. CoroutineLock coroutineLock = null;
  487. try
  488. {
  489. coroutineLock = await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, abInfo.Name.GetHashCode());
  490. if (abInfo.IsDisposed || abInfo.AlreadyLoadAssets)
  491. {
  492. return;
  493. }
  494. if (abInfo.AssetBundle != null && !abInfo.AssetBundle.isStreamedSceneAssetBundle)
  495. {
  496. // 异步load资源到内存cache住
  497. var assets = await AssetBundleHelper.UnityLoadAssetAsync(abInfo.AssetBundle);
  498. foreach (UnityEngine.Object asset in assets)
  499. {
  500. AddResource(abInfo.Name, asset.name, asset);
  501. }
  502. }
  503. abInfo.AlreadyLoadAssets = true;
  504. }
  505. finally
  506. {
  507. coroutineLock?.Dispose();
  508. }
  509. }
  510. public string DebugString()
  511. {
  512. StringBuilder sb = new StringBuilder();
  513. foreach (ABInfo abInfo in this.bundles.Values)
  514. {
  515. sb.Append($"{abInfo.Name}:{abInfo.RefCount}\n");
  516. }
  517. return sb.ToString();
  518. }
  519. }
  520. }