ResourcesComponent.cs 23 KB

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