TextureLoadHelp.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using UnityEngine;
  7. using UnityEngine.Networking;
  8. using UnityEngine.UI;
  9. public class TextureLoadHelp : MonoBehaviour
  10. {
  11. public static TextureLoadHelp _Instance;
  12. private Dictionary<string, TempTexData> tempTexList;
  13. private Dictionary<long, Material> waitLoadImgActionList;
  14. public float currentTotalSize = 0;
  15. public float maxSize = 500; //图片缓存-m
  16. private Dictionary<string, AssetBundle> loadDoneABList;
  17. private Dictionary<string, int> loadingABList;
  18. public Texture map_def;
  19. private void Awake()
  20. {
  21. _Instance = this;
  22. tempTexList = new Dictionary<string, TempTexData>();
  23. waitLoadImgActionList = new Dictionary<long, Material>();
  24. loadDoneABList = new Dictionary<string, AssetBundle>();
  25. loadingABList = new Dictionary<string, int>();
  26. }
  27. /// <summary>
  28. /// 加载图片
  29. /// </summary>
  30. /// <param name="path"></param>
  31. /// <param name="mat"></param>
  32. /// <returns></returns>
  33. public long LoadTexFromUrl(string path, Material mat)
  34. {
  35. long loadId = GetDownId();
  36. if (CheckCache(path))
  37. {
  38. mat.mainTexture = LoadFromCache(path);
  39. return 0;
  40. }
  41. if (tempTexList.TryGetValue(path, out var value))
  42. {
  43. value.isUsing = true;
  44. mat.mainTexture = value.tex;
  45. loadId = 0;
  46. }
  47. else
  48. {
  49. waitLoadImgActionList.Add(loadId, mat);
  50. StartCoroutine(DownLoadTex(path, loadId));
  51. }
  52. return loadId;
  53. }
  54. public long LoadTexFromUrl_AB(string ab_Name, string FileName, Material mat)
  55. {
  56. if (tempTexList.TryGetValue(FileName, out var value))
  57. {
  58. value.isUsing = true;
  59. mat.mainTexture = value.tex;
  60. return 0;
  61. }
  62. mat.mainTexture = map_def;
  63. long loadId = GetDownId();
  64. waitLoadImgActionList.Add(loadId, mat);
  65. StartCoroutine(DownLoadTex_AB(ab_Name, FileName, loadId));
  66. return loadId;
  67. }
  68. /// <summary>
  69. /// 取消加载
  70. /// </summary>
  71. /// <param name="loadId"></param>
  72. public void CancelLoad(long loadId)
  73. {
  74. if (waitLoadImgActionList.ContainsKey(loadId))
  75. {
  76. waitLoadImgActionList.Remove(loadId);
  77. }
  78. }
  79. /// <summary>
  80. /// 标记缓存图片为未使用
  81. /// </summary>
  82. /// <param name="path"></param>
  83. public void UnUsingTex(string path)
  84. {
  85. if (tempTexList.TryGetValue(path, out TempTexData disposeData))
  86. {
  87. disposeData.isUsing = false;
  88. }
  89. else
  90. {
  91. Debug.Log($"不存在缓存:{path}");
  92. }
  93. }
  94. IEnumerator DownLoadTex_AB(string ab_Name, string fileName, long loadId)
  95. {
  96. if (loadingABList.ContainsKey(ab_Name))
  97. {
  98. //Debug.Log($"{ab_Name} downloading...wait");
  99. yield return new WaitUntil(() => loadingABList[ab_Name] > 0);
  100. // if (loadingABList.ContainsKey(ab_Name))
  101. // {
  102. // loadingABList.Remove(ab_Name);
  103. // }
  104. }
  105. AssetBundle tempAb;
  106. Texture2D tex;
  107. if (loadDoneABList.TryGetValue(ab_Name, out var value))
  108. {
  109. tempAb = value;
  110. tex = tempAb.LoadAsset<Texture2D>(fileName);
  111. if (waitLoadImgActionList.TryGetValue(loadId, out Material targetMat))
  112. {
  113. if (targetMat != null && tex != null)
  114. {
  115. targetMat.mainTexture = tex;
  116. }
  117. else
  118. {
  119. if (targetMat == null)
  120. {
  121. Debug.Log($"{fileName} 材质球不存在");
  122. }
  123. if (tex == null)
  124. {
  125. Debug.Log($"{fileName} 图片不存在");
  126. }
  127. }
  128. waitLoadImgActionList.Remove(loadId);
  129. }
  130. }
  131. else
  132. {
  133. //添加到正在下载
  134. loadingABList.TryAdd(ab_Name, 0);
  135. #if UNITY_EDITOR
  136. WWW www = new WWW($"{Application.streamingAssetsPath}/{ab_Name}");
  137. #else
  138. WWW www = WWW.LoadFromCacheOrDownload($"{Application.streamingAssetsPath}/{ab_Name}",0);
  139. #endif
  140. yield return www;
  141. if (www.isDone)
  142. {
  143. tempAb = www.assetBundle;
  144. loadDoneABList.Add(ab_Name, tempAb);
  145. loadingABList[ab_Name] = 1;
  146. tex = tempAb.LoadAsset<Texture2D>(fileName);
  147. tempTexList.TryAdd(fileName, new TempTexData()
  148. {
  149. loadTime = GetTimeStamp(),
  150. name = fileName,
  151. tex = tex,
  152. size = 0,
  153. isUsing = true
  154. });
  155. if (waitLoadImgActionList.TryGetValue(loadId, out Material targetMat))
  156. {
  157. if (targetMat != null && tex != null)
  158. {
  159. targetMat.mainTexture = tex;
  160. }
  161. else
  162. {
  163. if (targetMat == null)
  164. {
  165. Debug.Log($"{fileName} 材质球不存在");
  166. }
  167. if (tex == null)
  168. {
  169. Debug.Log($"{fileName} 图片不存在");
  170. }
  171. }
  172. waitLoadImgActionList.Remove(loadId);
  173. }
  174. }
  175. else
  176. {
  177. loadingABList[ab_Name] = 2;
  178. Debug.LogError($"{ab_Name}下载失败:{www.error}");
  179. }
  180. www.Dispose();
  181. }
  182. }
  183. IEnumerator DownLoadTex(string path, long loadId)
  184. {
  185. UnityWebRequest www = UnityWebRequestTexture.GetTexture(path);
  186. yield return www.SendWebRequest();
  187. if (www.downloadHandler.isDone)
  188. {
  189. if (waitLoadImgActionList.ContainsKey(loadId))
  190. {
  191. var texture = ((DownloadHandlerTexture)www.downloadHandler).texture;
  192. float tempSize = GetSize_m(www.downloadedBytes);
  193. tempTexList.TryAdd(path, new TempTexData()
  194. {
  195. loadTime = GetTimeStamp(),
  196. name = path,
  197. tex = texture,
  198. size = tempSize,
  199. isUsing = true
  200. });
  201. currentTotalSize += tempSize;
  202. CheckSize();
  203. if (waitLoadImgActionList.TryGetValue(loadId, out Material targetMat))
  204. {
  205. if (targetMat != null)
  206. {
  207. targetMat.mainTexture = texture;
  208. }
  209. waitLoadImgActionList.Remove(loadId);
  210. }
  211. SaveInCache(path, www.downloadHandler.data);
  212. }
  213. else
  214. {
  215. www.disposeDownloadHandlerOnDispose = true;
  216. Debug.Log(path + " 下载已取消");
  217. }
  218. }
  219. else
  220. {
  221. Debug.LogError($"{path}下载失败:{www.downloadHandler.error}");
  222. }
  223. www.Dispose();
  224. }
  225. private void SaveInCache(string url, byte[] data)
  226. {
  227. string fileName = Path.GetFileName(url);
  228. string path = Application.persistentDataPath;
  229. File.WriteAllBytes(path + fileName, data);
  230. Debug.Log($"缓存:{path}{fileName}");
  231. }
  232. private Texture2D LoadFromCache(string url)
  233. {
  234. string fileName = Path.GetFileName(url);
  235. string path = Application.persistentDataPath;
  236. byte[] texBytes = File.ReadAllBytes(path + fileName);
  237. currentTotalSize += GetSize_m((ulong)texBytes.Length);
  238. Texture2D tempTex = new Texture2D(2, 2);
  239. tempTex.LoadImage(texBytes);
  240. tempTex.Apply();
  241. return tempTex;
  242. }
  243. private bool CheckCache(string url)
  244. {
  245. string fileName = Path.GetFileName(url);
  246. string path = Application.persistentDataPath;
  247. //Debug.Log($"CaChe:{path}");
  248. return File.Exists(path + fileName);
  249. }
  250. public void CheckSize()
  251. {
  252. if (currentTotalSize >= maxSize)
  253. {
  254. List<TempTexData> values = tempTexList.Values.ToList();
  255. values.Sort();
  256. for (int i = 0; i < values.Count; i++)
  257. {
  258. if (!values[i].isUsing)
  259. {
  260. if (tempTexList.TryGetValue(values[i].name, out TempTexData disposeData))
  261. {
  262. disposeData.tex = null;
  263. currentTotalSize -= disposeData.size;
  264. tempTexList.Remove(disposeData.name);
  265. }
  266. }
  267. if (currentTotalSize < maxSize)
  268. {
  269. break;
  270. }
  271. }
  272. if (currentTotalSize >= maxSize)
  273. {
  274. Debug.Log($"临时图片已超过限制大小且无可释放项!!!:{currentTotalSize}/{maxSize}");
  275. }
  276. }
  277. }
  278. /// <summary>
  279. /// 清空全部缓存
  280. /// </summary>
  281. public void ClearAllTempTex()
  282. {
  283. List<TempTexData> values = tempTexList.Values.ToList();
  284. for (int i = 0; i < values.Count; i++)
  285. {
  286. if (tempTexList.TryGetValue(values[i].name, out TempTexData disposeData))
  287. {
  288. disposeData.tex = null;
  289. currentTotalSize -= disposeData.size;
  290. tempTexList.Remove(disposeData.name);
  291. }
  292. }
  293. waitLoadImgActionList.Clear();
  294. tempTexList.Clear();
  295. Resources.UnloadUnusedAssets();
  296. GC.Collect();
  297. }
  298. private long GetDownId()
  299. {
  300. long id = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
  301. while (waitLoadImgActionList.ContainsKey(id))
  302. {
  303. id++;
  304. }
  305. return id;
  306. }
  307. private long GetTimeStamp()
  308. {
  309. return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
  310. }
  311. private float GetSize_m(ulong size_b)
  312. {
  313. return (size_b * 1.0f / (1024.0f * 1024.0f));
  314. }
  315. }
  316. public class TempTexData : IComparable<TempTexData>
  317. {
  318. public string name;
  319. public Texture tex;
  320. public long loadTime;
  321. public float size;
  322. public bool isUsing = true;
  323. public int CompareTo(TempTexData other)
  324. {
  325. if (other.loadTime < loadTime)
  326. {
  327. return 1;
  328. }
  329. if (other.loadTime == loadTime)
  330. {
  331. return 0;
  332. }
  333. return -1;
  334. }
  335. }