ResourcesComponent.cs 23 KB

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