TextureLoadHelp.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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)
  114. {
  115. targetMat.mainTexture = tex;
  116. }
  117. waitLoadImgActionList.Remove(loadId);
  118. }
  119. }
  120. else
  121. {
  122. //添加到正在下载
  123. loadingABList.TryAdd(ab_Name,0);
  124. WWW www = WWW.LoadFromCacheOrDownload($"{Application.streamingAssetsPath}/{ab_Name}",0);
  125. yield return www;
  126. if (www.isDone)
  127. {
  128. tempAb = www.assetBundle;
  129. loadDoneABList.Add(ab_Name,tempAb);
  130. loadingABList[ab_Name]=1;
  131. tex=tempAb.LoadAsset<Texture2D>(fileName);
  132. tempTexList.TryAdd(fileName, new TempTexData()
  133. {
  134. loadTime = GetTimeStamp(),
  135. name = fileName,
  136. tex = tex,
  137. size = 0,
  138. isUsing = true
  139. });
  140. if (waitLoadImgActionList.TryGetValue(loadId, out Material targetMat))
  141. {
  142. if (targetMat != null)
  143. {
  144. targetMat.mainTexture = tex;
  145. }
  146. waitLoadImgActionList.Remove(loadId);
  147. }
  148. }
  149. else
  150. {
  151. loadingABList[ab_Name]=2;
  152. Debug.LogError($"{ab_Name}下载失败:{www.error}");
  153. }
  154. www.Dispose();
  155. }
  156. }
  157. IEnumerator DownLoadTex(string path, long loadId)
  158. {
  159. UnityWebRequest www = UnityWebRequestTexture.GetTexture(path);
  160. yield return www.SendWebRequest();
  161. if (www.downloadHandler.isDone)
  162. {
  163. if (waitLoadImgActionList.ContainsKey(loadId))
  164. {
  165. var texture = ((DownloadHandlerTexture)www.downloadHandler).texture;
  166. float tempSize = GetSize_m(www.downloadedBytes);
  167. tempTexList.TryAdd(path, new TempTexData()
  168. {
  169. loadTime = GetTimeStamp(),
  170. name = path,
  171. tex = texture,
  172. size = tempSize,
  173. isUsing = true
  174. });
  175. currentTotalSize += tempSize;
  176. CheckSize();
  177. if (waitLoadImgActionList.TryGetValue(loadId, out Material targetMat))
  178. {
  179. if (targetMat != null)
  180. {
  181. targetMat.mainTexture = texture;
  182. }
  183. waitLoadImgActionList.Remove(loadId);
  184. }
  185. SaveInCache(path, www.downloadHandler.data);
  186. }
  187. else
  188. {
  189. www.disposeDownloadHandlerOnDispose = true;
  190. Debug.Log(path + " 下载已取消");
  191. }
  192. }
  193. else
  194. {
  195. Debug.LogError($"{path}下载失败:{www.downloadHandler.error}");
  196. }
  197. www.Dispose();
  198. }
  199. private void SaveInCache(string url,byte[] data)
  200. {
  201. string fileName = Path.GetFileName(url);
  202. string path = Application.persistentDataPath;
  203. File.WriteAllBytes(path+fileName,data);
  204. Debug.Log($"缓存:{path}{fileName}");
  205. }
  206. private Texture2D LoadFromCache(string url)
  207. {
  208. string fileName = Path.GetFileName(url);
  209. string path = Application.persistentDataPath;
  210. byte[] texBytes=File.ReadAllBytes(path+fileName);
  211. currentTotalSize += GetSize_m((ulong)texBytes.Length);
  212. Texture2D tempTex = new Texture2D(2,2);
  213. tempTex.LoadImage(texBytes);
  214. tempTex.Apply();
  215. return tempTex;
  216. }
  217. private bool CheckCache(string url)
  218. {
  219. string fileName = Path.GetFileName(url);
  220. string path = Application.persistentDataPath;
  221. //Debug.Log($"CaChe:{path}");
  222. return File.Exists(path + fileName);
  223. }
  224. public void CheckSize()
  225. {
  226. if (currentTotalSize >= maxSize)
  227. {
  228. List<TempTexData> values = tempTexList.Values.ToList();
  229. values.Sort();
  230. for (int i = 0; i < values.Count; i++)
  231. {
  232. if (!values[i].isUsing)
  233. {
  234. if (tempTexList.TryGetValue(values[i].name, out TempTexData disposeData))
  235. {
  236. disposeData.tex = null;
  237. currentTotalSize -= disposeData.size;
  238. tempTexList.Remove(disposeData.name);
  239. }
  240. }
  241. if (currentTotalSize < maxSize)
  242. {
  243. break;
  244. }
  245. }
  246. if (currentTotalSize >= maxSize)
  247. {
  248. Debug.Log($"临时图片已超过限制大小且无可释放项!!!:{currentTotalSize}/{maxSize}");
  249. }
  250. }
  251. }
  252. /// <summary>
  253. /// 清空全部缓存
  254. /// </summary>
  255. public void ClearAllTempTex()
  256. {
  257. List<TempTexData> values = tempTexList.Values.ToList();
  258. for (int i = 0; i < values.Count; i++)
  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. waitLoadImgActionList.Clear();
  268. tempTexList.Clear();
  269. Resources.UnloadUnusedAssets();
  270. GC.Collect();
  271. }
  272. private long GetDownId()
  273. {
  274. long id = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
  275. while (waitLoadImgActionList.ContainsKey(id))
  276. {
  277. id++;
  278. }
  279. return id;
  280. }
  281. private long GetTimeStamp()
  282. {
  283. return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
  284. }
  285. private float GetSize_m(ulong size_b)
  286. {
  287. return (size_b*1.0f / (1024.0f * 1024.0f));
  288. }
  289. }
  290. public class TempTexData : IComparable<TempTexData>
  291. {
  292. public string name;
  293. public Texture tex;
  294. public long loadTime;
  295. public float size;
  296. public bool isUsing = true;
  297. public int CompareTo(TempTexData other)
  298. {
  299. if (other.loadTime < loadTime)
  300. {
  301. return 1;
  302. }
  303. if (other.loadTime == loadTime)
  304. {
  305. return 0;
  306. }
  307. return -1;
  308. }
  309. }