ResourcesComponent.cs 21 KB

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