ResourcesComponent.cs 22 KB

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