ResourcesComponent.cs 22 KB

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