ResourcesComponent.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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 = new string[0];
  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. public async ETTask UnloadBundles(List<string> bundleList, bool unload = true)
  230. {
  231. int i = 0;
  232. foreach (string bundle in bundleList)
  233. {
  234. using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, bundle.GetHashCode()))
  235. {
  236. if (++i % 5 == 0)
  237. {
  238. await TimerComponent.Instance.WaitFrameAsync();
  239. }
  240. this.UnloadBundle(bundle, unload);
  241. }
  242. }
  243. }
  244. // 只允许场景设置unload为false
  245. public void UnloadBundle(string assetBundleName, bool unload = true)
  246. {
  247. assetBundleName = assetBundleName.BundleNameToLower();
  248. string[] dependencies = GetSortedDependencies(assetBundleName);
  249. //Log.Debug($"-----------dep unload start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  250. foreach (string dependency in dependencies)
  251. {
  252. this.UnloadOneBundle(dependency, unload);
  253. }
  254. //Log.Debug($"-----------dep unload finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  255. }
  256. private void UnloadOneBundle(string assetBundleName, bool unload = true)
  257. {
  258. assetBundleName = assetBundleName.BundleNameToLower();
  259. ABInfo abInfo;
  260. if (!this.bundles.TryGetValue(assetBundleName, out abInfo))
  261. {
  262. return;
  263. }
  264. //Log.Debug($"---------------unload one bundle {assetBundleName} refcount: {abInfo.RefCount - 1}");
  265. --abInfo.RefCount;
  266. if (abInfo.RefCount > 0)
  267. {
  268. return;
  269. }
  270. //Log.Debug($"---------------truly unload one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  271. this.bundles.Remove(assetBundleName);
  272. this.resourceCache.Remove(assetBundleName);
  273. abInfo.Destroy(unload);
  274. // Log.Debug($"cache count: {this.cacheDictionary.Count}");
  275. }
  276. /// <summary>
  277. /// 同步加载assetbundle
  278. /// </summary>
  279. /// <param name="assetBundleName"></param>
  280. /// <returns></returns>
  281. public void LoadBundle(string assetBundleName)
  282. {
  283. assetBundleName = assetBundleName.ToLower();
  284. string[] dependencies = GetSortedDependencies(assetBundleName);
  285. //Log.Debug($"-----------dep load start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  286. foreach (string dependency in dependencies)
  287. {
  288. if (string.IsNullOrEmpty(dependency))
  289. {
  290. continue;
  291. }
  292. this.LoadOneBundle(dependency);
  293. }
  294. //Log.Debug($"-----------dep load finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  295. }
  296. private void AddResource(string bundleName, string assetName, UnityEngine.Object resource)
  297. {
  298. Dictionary<string, UnityEngine.Object> dict;
  299. if (!this.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
  300. {
  301. dict = new Dictionary<string, UnityEngine.Object>();
  302. this.resourceCache[bundleName] = dict;
  303. }
  304. dict[assetName] = resource;
  305. }
  306. private void LoadOneBundle(string assetBundleName)
  307. {
  308. assetBundleName = assetBundleName.BundleNameToLower();
  309. ABInfo abInfo;
  310. if (this.bundles.TryGetValue(assetBundleName, out abInfo))
  311. {
  312. ++abInfo.RefCount;
  313. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  314. return;
  315. }
  316. if (!Define.IsAsync)
  317. {
  318. #if UNITY_EDITOR
  319. string[] realPath = null;
  320. realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
  321. foreach (string s in realPath)
  322. {
  323. string assetName = Path.GetFileNameWithoutExtension(s);
  324. UnityEngine.Object resource = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(s);
  325. AddResource(assetBundleName, assetName, resource);
  326. }
  327. if (realPath.Length > 0)
  328. {
  329. abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, null);
  330. this.bundles[assetBundleName] = abInfo;
  331. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  332. }
  333. else
  334. {
  335. Log.Error($"assets bundle not found: {assetBundleName}");
  336. }
  337. #endif
  338. return;
  339. }
  340. string p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
  341. AssetBundle assetBundle = null;
  342. if (File.Exists(p))
  343. {
  344. assetBundle = AssetBundle.LoadFromFile(p);
  345. }
  346. else
  347. {
  348. p = Path.Combine(PathHelper.AppResPath, assetBundleName);
  349. assetBundle = AssetBundle.LoadFromFile(p);
  350. }
  351. if (assetBundle == null)
  352. {
  353. // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
  354. Log.Warning($"assets bundle not found: {assetBundleName}");
  355. return;
  356. }
  357. if (!assetBundle.isStreamedSceneAssetBundle)
  358. {
  359. // 异步load资源到内存cache住
  360. var assets = assetBundle.LoadAllAssets();
  361. foreach (UnityEngine.Object asset in assets)
  362. {
  363. AddResource(assetBundleName, asset.name, asset);
  364. }
  365. }
  366. abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, assetBundle);
  367. this.bundles[assetBundleName] = abInfo;
  368. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  369. }
  370. /// <summary>
  371. /// 异步加载assetbundle, 加载ab包分两部分,第一部分是从硬盘加载,第二部分加载all assets。两者不能同时并发
  372. /// </summary>
  373. public async ETTask LoadBundleAsync(string assetBundleName)
  374. {
  375. assetBundleName = assetBundleName.BundleNameToLower();
  376. string[] dependencies = GetSortedDependencies(assetBundleName);
  377. //Log.Debug($"-----------dep load async start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  378. using (var abInfos = ListComponent<ABInfo>.Create())
  379. {
  380. async ETTask LoadDependency(string dependency, List<ABInfo> abInfosList)
  381. {
  382. using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, dependency.GetHashCode()))
  383. {
  384. ABInfo abInfo = await this.LoadOneBundleAsync(dependency);
  385. if (abInfo == null || abInfo.RefCount > 1)
  386. {
  387. return;
  388. }
  389. abInfosList.Add(abInfo);
  390. }
  391. }
  392. // LoadFromFileAsync部分可以并发加载
  393. using (var tasks = ListComponent<ETTask>.Create())
  394. {
  395. foreach (string dependency in dependencies)
  396. {
  397. tasks.List.Add(LoadDependency(dependency, abInfos.List));
  398. }
  399. await ETTaskHelper.WaitAll(tasks.List);
  400. }
  401. // ab包从硬盘加载完成,可以再并发加载all assets
  402. using (var tasks = ListComponent<ETTask>.Create())
  403. {
  404. foreach (ABInfo abInfo in abInfos.List)
  405. {
  406. tasks.List.Add(LoadOneBundleAllAssets(abInfo));
  407. }
  408. await ETTaskHelper.WaitAll(tasks.List);
  409. }
  410. }
  411. }
  412. private async ETTask<ABInfo> LoadOneBundleAsync(string assetBundleName)
  413. {
  414. assetBundleName = assetBundleName.BundleNameToLower();
  415. ABInfo abInfo;
  416. if (this.bundles.TryGetValue(assetBundleName, out abInfo))
  417. {
  418. ++abInfo.RefCount;
  419. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  420. return null;
  421. }
  422. string p = "";
  423. AssetBundle assetBundle = null;
  424. if (!Define.IsAsync)
  425. {
  426. #if UNITY_EDITOR
  427. string[] realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
  428. foreach (string s in realPath)
  429. {
  430. string assetName = Path.GetFileNameWithoutExtension(s);
  431. UnityEngine.Object resource = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(s);
  432. AddResource(assetBundleName, assetName, resource);
  433. }
  434. if (realPath.Length > 0)
  435. {
  436. abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, null);
  437. this.bundles[assetBundleName] = abInfo;
  438. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  439. }
  440. else
  441. {
  442. Log.Error("Bundle not exist! BundleName: " + assetBundleName);
  443. }
  444. // 编辑器模式也不能同步加载
  445. await TimerComponent.Instance.WaitAsync(100);
  446. #endif
  447. return abInfo;
  448. }
  449. p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
  450. if (!File.Exists(p))
  451. {
  452. p = Path.Combine(PathHelper.AppResPath, assetBundleName);
  453. }
  454. Log.Info("Async load bundle BundleName : " + p);
  455. // if (!File.Exists(p))
  456. // {
  457. // Log.Error("Async load bundle not exist! BundleName : " + p);
  458. // return null;
  459. // }
  460. assetBundle = await AssetBundleHelper.UnityLoadBundleAsync(p);
  461. if (assetBundle == null)
  462. {
  463. // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
  464. Log.Warning($"assets bundle not found: {assetBundleName}");
  465. return null;
  466. }
  467. abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, assetBundle);
  468. this.bundles[assetBundleName] = abInfo;
  469. return abInfo;
  470. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  471. }
  472. // 加载ab包中的all assets
  473. private async ETTask LoadOneBundleAllAssets(ABInfo abInfo)
  474. {
  475. using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, abInfo.Name.GetHashCode()))
  476. {
  477. if (abInfo.IsDisposed || abInfo.AlreadyLoadAssets)
  478. {
  479. return;
  480. }
  481. if (abInfo.AssetBundle != null && !abInfo.AssetBundle.isStreamedSceneAssetBundle)
  482. {
  483. // 异步load资源到内存cache住
  484. var assets = await AssetBundleHelper.UnityLoadAssetAsync(abInfo.AssetBundle);
  485. foreach (UnityEngine.Object asset in assets)
  486. {
  487. AddResource(abInfo.Name, asset.name, asset);
  488. }
  489. }
  490. abInfo.AlreadyLoadAssets = true;
  491. }
  492. }
  493. public string DebugString()
  494. {
  495. StringBuilder sb = new StringBuilder();
  496. foreach (ABInfo abInfo in this.bundles.Values)
  497. {
  498. sb.Append($"{abInfo.Name}:{abInfo.RefCount}\n");
  499. }
  500. return sb.ToString();
  501. }
  502. }
  503. }