ExtralLoadHandler.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. using System;
  2. using System.Collections;
  3. using System.IO;
  4. using UnityEngine;
  5. using UnityEngine.Networking;
  6. using XRTool.Util;
  7. using Newtonsoft.Json;
  8. using TriLibCore;
  9. using TriLibCore.Mappers;
  10. using TriLibCore.Utils;
  11. namespace ShadowStudio.Model
  12. {
  13. public enum ArtState
  14. {
  15. UnLoad = -1,
  16. Loading = 0,
  17. Loaded = 1
  18. }
  19. /// <summary>
  20. /// 外部资源加载
  21. /// 可能是模型 zip文件
  22. /// 可能是图片
  23. /// 可能是视频,视频可在线播放,无需下载
  24. /// </summary>
  25. public class ExtralLoadHandler : ArtInstanceHandler
  26. {
  27. private ArtState artState = ArtState.UnLoad;
  28. private Action<float> loadPorcess;
  29. private Action<UnityEngine.Object> artLoaded;
  30. public override UnityEngine.Object InstanceArt()
  31. {
  32. return LoadCache;
  33. }
  34. /// <summary>
  35. /// 异步加载资源
  36. /// 此函数仅加载资源,不负责下载和解压
  37. /// 与异步获取icon不同,异步获取icon,当不存在文件时,会先下载资源再加载
  38. /// </summary>
  39. /// <param name="path"></param>
  40. /// <param name="process"></param>
  41. /// <param name="loaded"></param>
  42. /// <returns></returns>
  43. public override IEnumerator LoadAsyn(string path, Action<float> process, Action<UnityEngine.Object> loaded)
  44. {
  45. if (Info.ArtType == ArtType.Movies)
  46. {
  47. process?.Invoke(1);
  48. loaded(null);
  49. }
  50. else if (Info.ArtType == ArtType.Image)
  51. {
  52. Texture icon = GetIcon();
  53. yield return icon;
  54. if (icon)
  55. {
  56. LoadCache = icon;
  57. process?.Invoke(1);
  58. loaded?.Invoke(LoadCache);
  59. }
  60. else
  61. {
  62. GetIcon((tex) =>
  63. {
  64. LoadCache = tex;
  65. process?.Invoke(1);
  66. loaded?.Invoke(LoadCache);
  67. });
  68. }
  69. }
  70. else if (Info.ArtType == ArtType.Model)
  71. {
  72. if (LoadCache)
  73. {
  74. string cloneName = LoadCache.name;
  75. LoadCache = GameObject.Instantiate(LoadCache);
  76. LoadCache.name = cloneName;
  77. loaded?.Invoke(LoadCache);
  78. yield break;
  79. }
  80. if (artState == ArtState.Loading)
  81. {
  82. loadPorcess += (p) => process?.Invoke(p);
  83. artLoaded += (obj) =>
  84. {
  85. string cloneName = LoadCache.name;
  86. LoadCache = GameObject.Instantiate(LoadCache);
  87. LoadCache.name = cloneName;
  88. loaded?.Invoke(LoadCache);
  89. artLoaded = null;
  90. loadPorcess = null;
  91. };
  92. yield break;
  93. }
  94. if (artState == ArtState.UnLoad)
  95. {
  96. artState = ArtState.Loading;
  97. }
  98. string url = Info.Url;
  99. string serverPath = Path.Combine(BuildConfig.Instance.ServerUrl, url);
  100. string filePath = Path.Combine(localExtralPath, GetFilePath(url));
  101. try
  102. {
  103. ///文件不存在,下载
  104. ///模型的图例?是否下载呢?是个问题
  105. if (!File.Exists(filePath))
  106. {
  107. TimerMgr.Instance.StartCoroutine(DataFileUtil.DownLoadDataAsync(serverPath, filePath, (isComplete, handler) =>
  108. {
  109. if (handler != null)
  110. {
  111. LoadInternal(filePath, loaded);
  112. }
  113. else
  114. {
  115. UnityLog.LogError(JsonConvert.SerializeObject(Info) + "frist load error!");
  116. }
  117. }, null, (all, cur) =>
  118. {
  119. DownProcess = cur;
  120. process?.Invoke(cur);
  121. loadPorcess?.Invoke(cur);
  122. }));
  123. //TimerMgr.Instance.StartCoroutine(DataFileUtil.DownLoadData(serverPath, filePath, (isComplete, handler) =>
  124. // {
  125. // if (handler != null)
  126. // {
  127. // LoadInternal(filePath, loaded, handler.downloadHandler.data);
  128. // }
  129. // else
  130. // {
  131. // UnityLog.LogError(JsonConvert.SerializeObject(Info) + "frist load error!");
  132. // }
  133. // }, null, (all, cur) =>
  134. // {
  135. // DownProcess = cur;
  136. // process?.Invoke(cur);
  137. // loadPorcess?.Invoke(cur);
  138. // }));
  139. }
  140. else
  141. {
  142. //TimerMgr.Instance.StartCoroutine(DataFileUtil.RequestDownData(filePath, (tmppath, handler) =>
  143. //{
  144. // LoadInternal(filePath, loaded, handler.downloadHandler != null ? handler.downloadHandler.data : null);
  145. //}, null, (all, cur) =>
  146. // {
  147. // DownProcess = cur;
  148. // process?.Invoke(cur);
  149. // loadPorcess?.Invoke(cur);
  150. // }));
  151. LoadInternal(filePath, loaded);
  152. }
  153. }
  154. catch
  155. {
  156. loaded?.Invoke(null);
  157. UnityLog.LogError(Info.ArtId + "load exception!");
  158. }
  159. }
  160. yield return null;
  161. }
  162. /// <summary>
  163. /// 加载模型
  164. /// </summary>
  165. /// <param name="filePath"></param>
  166. /// <param name="loaded"></param>
  167. private void LoadModel(string filePath, Action<UnityEngine.Object> loaded)
  168. {
  169. //using (var assetLoader = new AssetLoaderAsync())
  170. //{
  171. // try
  172. // {
  173. // var assetLoaderOptions = AssetLoaderOptions.CreateInstance();
  174. // assetLoaderOptions.RotationAngles = new Vector3(90f, 180f, 0f);
  175. // assetLoaderOptions.AutoPlayAnimations = true;
  176. // assetLoader.LoadFromFile(filePath, assetLoaderOptions, null, (loadedGameObject) =>
  177. // {
  178. // LoadCache = loadedGameObject;
  179. // loaded?.Invoke(loadedGameObject);
  180. // });
  181. // }
  182. // catch (Exception e)
  183. // {
  184. // Debug.LogError(e.ToString());
  185. // loaded?.Invoke(null);
  186. // }
  187. //}
  188. }
  189. private AssetLoaderOptions GetAssetLoaderOptions()
  190. {
  191. //var assetLoaderOptions = AssetLoaderOptions.CreateInstance();
  192. //assetLoaderOptions.DontLoadCameras = false;
  193. //assetLoaderOptions.DontLoadLights = false;
  194. //assetLoaderOptions.UseCutoutMaterials = false;
  195. //assetLoaderOptions.AddAssetUnloader = true;
  196. //return assetLoaderOptions;
  197. return null;
  198. }
  199. private void OnLoad(AssetLoaderContext assetLoaderContext)
  200. {
  201. //if (_loadedGameObject != null)
  202. //{
  203. // Destroy(_loadedGameObject);
  204. //}
  205. //_loadedGameObject = assetLoaderContext.RootGameObject;
  206. //if (_loadedGameObject != null)
  207. //{
  208. // Camera.main.FitToBounds(assetLoaderContext.RootGameObject, 2f);
  209. // Debug.Log("Model loaded. Loading materials.");
  210. //}
  211. //else
  212. //{
  213. // Debug.Log("Model materials could not be loaded.");
  214. //}
  215. //_loadModelButton.interactable = true;
  216. }
  217. /// <summary>
  218. /// 更改层级
  219. /// </summary>
  220. /// <param name="parentTransform"></param>
  221. public void ChangeLayerRecursively(Transform parentTransform)
  222. {
  223. // 修改父物体的层级
  224. parentTransform.gameObject.layer = LayerMask.NameToLayer("Arrow");
  225. // 遍历所有子物体,并递归调用ChangeLayerRecursively方法
  226. for (int i = 0; i < parentTransform.childCount; i++)
  227. {
  228. Transform childTransform = parentTransform.GetChild(i);
  229. ChangeLayerRecursively(childTransform);
  230. }
  231. }
  232. private void LoadInternal(string filename, Action<UnityEngine.Object> loaded)
  233. {
  234. TriLibModelLoad.Load(filename, (AssetLoaderContext ac) => {
  235. Debug.Log("模型加载完成");
  236. }, (AssetLoaderContext ac) => {
  237. Debug.Log("载材质加完成");
  238. ChangeLayerRecursively(ac.RootGameObject.transform);
  239. LoadCache = ac.RootGameObject;
  240. loaded?.Invoke(LoadCache);
  241. artLoaded?.Invoke(LoadCache);
  242. artState = ArtState.Loaded;
  243. }, (AssetLoaderContext ac, float f) => {
  244. Debug.Log("加载中==》" + f);
  245. }, (IContextualizedError error) => {
  246. loaded?.Invoke(null);
  247. artLoaded?.Invoke(null);
  248. artState = ArtState.UnLoad;
  249. UnityLog.LogError(Info.ArtId + "资源加载失败");
  250. });
  251. return;
  252. //var modelFileWithStream = FindModelFile();
  253. var modelFilename = Path.GetFileName(filename);
  254. var modelStream = File.OpenRead(filename);
  255. var _assetLoaderOptions = AssetLoader.CreateDefaultLoaderOptions();
  256. _assetLoaderOptions.TextureMapper = ScriptableObject.CreateInstance<FilePickerTextureMapper>();
  257. _assetLoaderOptions.ExternalDataMapper = ScriptableObject.CreateInstance<FilePickerExternalDataMapper>();
  258. _assetLoaderOptions.FixedAllocations.Add(_assetLoaderOptions.ExternalDataMapper);
  259. _assetLoaderOptions.FixedAllocations.Add(_assetLoaderOptions.TextureMapper);
  260. var _modelExtension = modelFilename != null ? FileUtils.GetFileExtension(modelFilename, false) : null;
  261. if (_modelExtension == "zip")
  262. {
  263. if (modelStream != null)
  264. {
  265. //AssetLoaderZip.LoadModelFromZipStream(modelStream, _onLoad, _onMaterialsLoad, _onProgress, _onError, _wrapperGameObject, _assetLoaderOptions, _items, null);
  266. AssetLoaderZip.LoadModelFromZipStream(modelStream, (t1) =>
  267. {
  268. LoadCache = t1.RootGameObject;
  269. loaded?.Invoke(LoadCache);
  270. artLoaded?.Invoke(LoadCache);
  271. artState = ArtState.Loaded;
  272. }, null, null,
  273. (t2) =>
  274. {
  275. loaded?.Invoke(null);
  276. artLoaded?.Invoke(null);
  277. artState = ArtState.UnLoad;
  278. UnityLog.LogError(Info.ArtId + "资源加载失败");
  279. }, null, _assetLoaderOptions, null, null);
  280. }
  281. else
  282. {
  283. //AssetLoaderZip.LoadModelFromZipFile(modelFilename, _onLoad, _onMaterialsLoad, _onProgress, _onError, _wrapperGameObject, _assetLoaderOptions, _items, null);
  284. AssetLoaderZip.LoadModelFromZipFile(modelFilename, (t1) =>
  285. {
  286. LoadCache = t1.RootGameObject;
  287. loaded?.Invoke(LoadCache);
  288. artLoaded?.Invoke(LoadCache);
  289. artState = ArtState.Loaded;
  290. }, null, null, (t2) =>
  291. {
  292. loaded?.Invoke(null);
  293. artLoaded?.Invoke(null);
  294. artState = ArtState.UnLoad;
  295. UnityLog.LogError(Info.ArtId + "资源加载失败");
  296. }, null, _assetLoaderOptions, null, null);
  297. }
  298. }
  299. else
  300. {
  301. if (modelStream != null)
  302. {
  303. //AssetLoader.LoadModelFromStream(modelStream, modelFilename, _modelExtension, _onLoad, _onMaterialsLoad, _onProgress, _onError, _wrapperGameObject, _assetLoaderOptions, _items);
  304. AssetLoader.LoadModelFromStream(modelStream, modelFilename, _modelExtension, (t2) =>
  305. {
  306. LoadCache = t2.RootGameObject;
  307. loaded?.Invoke(LoadCache);
  308. artLoaded?.Invoke(LoadCache);
  309. artState = ArtState.Loaded;
  310. }, null, null, (t2) =>
  311. {
  312. loaded?.Invoke(null);
  313. artLoaded?.Invoke(null);
  314. artState = ArtState.UnLoad;
  315. UnityLog.LogError(Info.ArtId + "资源加载失败");
  316. }, null, _assetLoaderOptions, null);
  317. }
  318. else
  319. {
  320. AssetLoader.LoadModelFromFile(modelFilename, (t2) =>
  321. {
  322. LoadCache = t2.RootGameObject;
  323. loaded?.Invoke(LoadCache);
  324. artLoaded?.Invoke(LoadCache);
  325. artState = ArtState.Loaded;
  326. }, null, null, (t2) =>
  327. {
  328. loaded?.Invoke(null);
  329. artLoaded?.Invoke(null);
  330. artState = ArtState.UnLoad;
  331. UnityLog.LogError(Info.ArtId + "资源加载失败");
  332. }, null, _assetLoaderOptions, null);
  333. }
  334. }
  335. //var assetLoaderOptions = AssetLoader.CreateDefaultLoaderOptions();
  336. //var assetLoaderFilePicker = AssetLoaderFilePicker.Create();
  337. //assetLoaderFilePicker.LoadModelFromFilePickerAsync("Select a Model file", (assetLoaderContext) =>
  338. //{
  339. // LoadCache = assetLoaderContext.RootGameObject;
  340. // loaded?.Invoke(LoadCache);
  341. // artLoaded?.Invoke(LoadCache);
  342. // artState = ArtState.Loaded;
  343. //}, OnMaterialsLoad, (t1, process) =>
  344. //{
  345. //}, (isfrist) => { }, (error) => { }, null, assetLoaderOptions);
  346. //AssetLoaderZip.LoadModelFromZipFile(modelFilename, _onLoad, _onMaterialsLoad, _onProgress, _onError, _wrapperGameObject, _assetLoaderOptions, _items, null);
  347. //_loadingTimer.Reset();
  348. //_loadingTimer.Start();
  349. //PreLoadSetup();
  350. //var assetLoaderOptions = GetAssetLoaderOptions();
  351. //using (var assetLoader = new AssetLoaderAsync())
  352. //{
  353. // //assetLoader.OnMetadataProcessed += AssetLoader_OnMetadataProcessed;
  354. // try
  355. // {
  356. // if (fileBytes != null && fileBytes.Length > 0)
  357. // {
  358. // var extension = FileUtils.GetFileExtension(filename);
  359. // assetLoader.LoadFromMemoryWithTextures(fileBytes, extension, assetLoaderOptions, null, delegate (GameObject loadedGameObject)
  360. // {
  361. // LoadCache = loadedGameObject;
  362. // loaded?.Invoke(LoadCache);
  363. // artLoaded?.Invoke(LoadCache);
  364. // artState = ArtState.Loaded;
  365. // });
  366. // }
  367. // else if (!string.IsNullOrEmpty(filename))
  368. // {
  369. // assetLoader.LoadFromFileWithTextures(filename, assetLoaderOptions, null, delegate (GameObject loadedGameObject)
  370. // {
  371. // LoadCache = loadedGameObject;
  372. // loaded?.Invoke(LoadCache);
  373. // artLoaded?.Invoke(LoadCache);
  374. // artState = ArtState.Loaded;
  375. // });
  376. // }
  377. // else
  378. // {
  379. // loaded?.Invoke(null);
  380. // artLoaded?.Invoke(null);
  381. // artState = ArtState.UnLoad;
  382. // throw new Exception("File not selected");
  383. // }
  384. // }
  385. // catch
  386. // {
  387. // loaded?.Invoke(null);
  388. // artLoaded?.Invoke(null);
  389. // artState = ArtState.UnLoad;
  390. // UnityLog.LogError(Info.ArtId + "资源加载失败");
  391. // }
  392. //}
  393. }
  394. private void OnMaterialsLoad(AssetLoaderContext obj)
  395. {
  396. //throw new NotImplementedException();
  397. }
  398. }
  399. }