AssetLoader.cs 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text.RegularExpressions;
  5. using StbImageSharp;
  6. using TriLibCore.Extensions;
  7. using TriLibCore.General;
  8. using TriLibCore.Interfaces;
  9. using TriLibCore.Mappers;
  10. using TriLibCore.Utils;
  11. using UnityEngine;
  12. using FileMode = System.IO.FileMode;
  13. using HumanDescription = UnityEngine.HumanDescription;
  14. using Object = UnityEngine.Object;
  15. #if TRILIB_DRACO
  16. using TriLibCore.Gltf.Draco;
  17. #endif
  18. #if UNITY_EDITOR
  19. using UnityEditor;
  20. #endif
  21. namespace TriLibCore
  22. {
  23. /// <summary>Represents the main class containing methods to load the Models.</summary>
  24. public static class AssetLoader
  25. {
  26. /// <summary>Loads a Model from the given path asynchronously.</summary>
  27. /// <param name="path">The Model file path.</param>
  28. /// <param name="onLoad">The Method to call on the Main Thread when the Model Meshes and hierarchy are loaded.</param>
  29. /// <param name="onMaterialsLoad">The Method to call on the Main Thread when the Model (including Textures and Materials) has been fully loaded.</param>
  30. /// <param name="onProgress">The Method to call when the Model loading progress changes.</param>
  31. /// <param name="onError">The Method to call on the Main Thread when any error occurs.</param>
  32. /// <param name="wrapperGameObject">The Game Object that will be the parent of the loaded Game Object. Can be null.</param>
  33. /// <param name="assetLoaderOptions">The Asset Loader Options reference. Asset Loader Options contains various options used during the Model loading process.</param>
  34. /// <param name="customContextData">The Custom Data that will be passed along the AssetLoaderContext.</param>
  35. /// <returns>The Asset Loader Context, containing Model loading information and the output Game Object.</returns>
  36. public static AssetLoaderContext LoadModelFromFile(string path, Action<AssetLoaderContext> onLoad, Action<AssetLoaderContext> onMaterialsLoad, Action<AssetLoaderContext, float> onProgress, Action<IContextualizedError> onError = null, GameObject wrapperGameObject = null, AssetLoaderOptions assetLoaderOptions = null, object customContextData = null)
  37. {
  38. #if UNITY_WEBGL || UNITY_UWP
  39. AssetLoaderContext assetLoaderContext = null;
  40. try
  41. {
  42. assetLoaderContext = LoadModelFromFileNoThread(path, onError, wrapperGameObject, assetLoaderOptions, customContextData);
  43. onLoad(assetLoaderContext);
  44. onMaterialsLoad(assetLoaderContext);
  45. }
  46. catch (Exception exception)
  47. {
  48. if (exception is IContextualizedError contextualizedError)
  49. {
  50. HandleError(contextualizedError);
  51. }
  52. else
  53. {
  54. HandleError(new ContextualizedError<AssetLoaderContext>(exception, null));
  55. }
  56. }
  57. return assetLoaderContext;
  58. #else
  59. var assetLoaderContext = new AssetLoaderContext
  60. {
  61. Options = assetLoaderOptions ? assetLoaderOptions : CreateDefaultLoaderOptions(),
  62. Filename = path,
  63. BasePath = FileUtils.GetFileDirectory(path),
  64. WrapperGameObject = wrapperGameObject,
  65. OnMaterialsLoad = onMaterialsLoad,
  66. OnLoad = onLoad,
  67. OnProgress = onProgress,
  68. HandleError = HandleError,
  69. OnError = onError,
  70. CustomData = customContextData,
  71. };
  72. assetLoaderContext.Tasks.Add(ThreadUtils.RunThread(assetLoaderContext, ref assetLoaderContext.CancellationToken, LoadModel, ProcessRootModel, HandleError, assetLoaderContext.Options != null ? assetLoaderContext.Options.Timeout : 0));
  73. return assetLoaderContext;
  74. #endif
  75. }
  76. /// <summary>Loads a Model from the given Stream asynchronously.</summary>
  77. /// <param name="stream">The Stream containing the Model data.</param>
  78. /// <param name="filename">The Model filename.</param>
  79. /// <param name="fileExtension">The Model file extension. (Eg.: fbx)</param>
  80. /// <param name="onLoad">The Method to call on the Main Thread when the Model Meshes and hierarchy are loaded.</param>
  81. /// <param name="onMaterialsLoad">The Method to call on the Main Thread when the Model (including Textures and Materials) has been fully loaded.</param>
  82. /// <param name="onProgress">The Method to call when the Model loading progress changes.</param>
  83. /// <param name="onError">The Method to call on the Main Thread when any error occurs.</param>
  84. /// <param name="wrapperGameObject">The Game Object that will be the parent of the loaded Game Object. Can be null.</param>
  85. /// <param name="assetLoaderOptions">The Asset Loader Options reference. Asset Loader Options contains various options used during the Model loading process.</param>
  86. /// <param name="customContextData">The Custom Data that will be passed along the AssetLoaderContext.</param>
  87. /// <returns>The Asset Loader Context, containing Model loading information and the output Game Object.</returns>
  88. public static AssetLoaderContext LoadModelFromStream(Stream stream, string filename = null, string fileExtension = null, Action<AssetLoaderContext> onLoad = null, Action<AssetLoaderContext> onMaterialsLoad = null, Action<AssetLoaderContext, float> onProgress = null, Action<IContextualizedError> onError = null, GameObject wrapperGameObject = null, AssetLoaderOptions assetLoaderOptions = null, object customContextData = null)
  89. {
  90. #if UNITY_WEBGL || UNITY_UWP
  91. AssetLoaderContext assetLoaderContext = null;
  92. try
  93. {
  94. assetLoaderContext = LoadModelFromStreamNoThread(stream, filename, fileExtension, onError, wrapperGameObject, assetLoaderOptions, customContextData);
  95. onLoad(assetLoaderContext);
  96. onMaterialsLoad(assetLoaderContext);
  97. }
  98. catch (Exception exception)
  99. {
  100. if (exception is IContextualizedError contextualizedError)
  101. {
  102. HandleError(contextualizedError);
  103. }
  104. else
  105. {
  106. HandleError(new ContextualizedError<AssetLoaderContext>(exception, null));
  107. }
  108. }
  109. return assetLoaderContext;
  110. #else
  111. var assetLoaderContext = new AssetLoaderContext
  112. {
  113. Options = assetLoaderOptions == null ? CreateDefaultLoaderOptions() : assetLoaderOptions,
  114. Stream = stream,
  115. FileExtension = fileExtension ?? FileUtils.GetFileExtension(filename, false),
  116. BasePath = FileUtils.GetFileDirectory(filename),
  117. WrapperGameObject = wrapperGameObject,
  118. OnMaterialsLoad = onMaterialsLoad,
  119. OnLoad = onLoad,
  120. HandleError = HandleError,
  121. OnError = onError,
  122. CustomData = customContextData
  123. };
  124. assetLoaderContext.Tasks.Add(ThreadUtils.RunThread(assetLoaderContext, ref assetLoaderContext.CancellationToken, LoadModel, ProcessRootModel, HandleError, assetLoaderContext.Options.Timeout));
  125. return assetLoaderContext;
  126. #endif
  127. }
  128. /// <summary>Loads a Model from the given path synchronously.</summary>
  129. /// <param name="path">The Model file path.</param>
  130. /// <param name="onError">The Method to call on the Main Thread when any error occurs.</param>
  131. /// <param name="wrapperGameObject">The Game Object that will be the parent of the loaded Game Object. Can be null.</param>
  132. /// <param name="assetLoaderOptions">The Asset Loader Options reference. Asset Loader Options contains various options used during the Model loading process.</param>
  133. /// <param name="customContextData">The Custom Data that will be passed along the AssetLoaderContext.</param>
  134. /// <returns>The Asset Loader Context, containing Model loading information and the output Game Object.</returns>
  135. public static AssetLoaderContext LoadModelFromFileNoThread(string path, Action<IContextualizedError> onError = null, GameObject wrapperGameObject = null, AssetLoaderOptions assetLoaderOptions = null, object customContextData = null)
  136. {
  137. var assetLoaderContext = new AssetLoaderContext
  138. {
  139. Options = assetLoaderOptions == null ? CreateDefaultLoaderOptions() : assetLoaderOptions,
  140. Filename = path,
  141. BasePath = FileUtils.GetFileDirectory(path),
  142. CustomData = customContextData,
  143. HandleError = HandleError,
  144. OnError = onError,
  145. WrapperGameObject = wrapperGameObject,
  146. Async = false
  147. };
  148. try
  149. {
  150. LoadModel(assetLoaderContext);
  151. ProcessRootModel(assetLoaderContext);
  152. }
  153. catch (Exception exception)
  154. {
  155. HandleError(new ContextualizedError<AssetLoaderContext>(exception, assetLoaderContext));
  156. }
  157. return assetLoaderContext;
  158. }
  159. /// <summary>Loads a Model from the given Stream synchronously.</summary>
  160. /// <param name="stream">The Stream containing the Model data.</param>
  161. /// <param name="filename">The Model filename.</param>
  162. /// <param name="fileExtension">The Model file extension. (Eg.: fbx)</param>
  163. /// <param name="onError">The Method to call on the Main Thread when any error occurs.</param>
  164. /// <param name="wrapperGameObject">The Game Object that will be the parent of the loaded Game Object. Can be null.</param>
  165. /// <param name="assetLoaderOptions">The Asset Loader Options reference. Asset Loader Options contains various options used during the Model loading process.</param>
  166. /// <param name="customContextData">The Custom Data that will be passed along the AssetLoaderContext.</param>
  167. /// <returns>The Asset Loader Context, containing Model loading information and the output Game Object.</returns>
  168. public static AssetLoaderContext LoadModelFromStreamNoThread(Stream stream, string filename = null, string fileExtension = null, Action<IContextualizedError> onError = null, GameObject wrapperGameObject = null, AssetLoaderOptions assetLoaderOptions = null, object customContextData = null)
  169. {
  170. var assetLoaderContext = new AssetLoaderContext
  171. {
  172. Options = assetLoaderOptions ? assetLoaderOptions : CreateDefaultLoaderOptions(),
  173. Stream = stream,
  174. FileExtension = fileExtension ?? FileUtils.GetFileExtension(filename, false),
  175. BasePath = FileUtils.GetFileDirectory(filename),
  176. CustomData = customContextData,
  177. HandleError = HandleError,
  178. OnError = onError,
  179. WrapperGameObject = wrapperGameObject,
  180. Async = false
  181. };
  182. try
  183. {
  184. LoadModel(assetLoaderContext);
  185. ProcessRootModel(assetLoaderContext);
  186. }
  187. catch (Exception exception)
  188. {
  189. HandleError(new ContextualizedError<AssetLoaderContext>(exception, assetLoaderContext));
  190. }
  191. return assetLoaderContext;
  192. }
  193. #if UNITY_EDITOR
  194. private static Object LoadOrCreateScriptableObject(string type, string subFolder)
  195. {
  196. string mappersFilePath;
  197. var triLibMapperAssets = AssetDatabase.FindAssets("TriLibMappersPlaceholder");
  198. if (triLibMapperAssets.Length > 0)
  199. {
  200. mappersFilePath = AssetDatabase.GUIDToAssetPath(triLibMapperAssets[0]);
  201. }
  202. else
  203. {
  204. throw new Exception("Could not find \"TriLibMappersPlaceholder\" file. Please re-import TriLib package.");
  205. }
  206. var mappersDirectory = $"{FileUtils.GetFileDirectory(mappersFilePath)}";
  207. var assetDirectory = $"{mappersDirectory}/{subFolder}";
  208. if (!AssetDatabase.IsValidFolder(assetDirectory))
  209. {
  210. AssetDatabase.CreateFolder(mappersDirectory, subFolder);
  211. }
  212. var assetPath = $"{assetDirectory}/{type}.asset";
  213. var scriptableObject = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Object));
  214. if (scriptableObject == null) {
  215. scriptableObject = ScriptableObject.CreateInstance(type);
  216. AssetDatabase.CreateAsset(scriptableObject, assetPath);
  217. }
  218. return scriptableObject;
  219. }
  220. #endif
  221. /// <summary>Creates an Asset Loader Options with the default options and Mappers using an existing pre-allocations List.</summary>
  222. /// <param name="generateAssets">Indicates whether created Scriptable Objects will be saved as assets.</param>
  223. /// <returns>The Asset Loader Options containing the default settings.</returns>
  224. public static AssetLoaderOptions CreateDefaultLoaderOptions(bool generateAssets = false)
  225. {
  226. var assetLoaderOptions = ScriptableObject.CreateInstance<AssetLoaderOptions>();
  227. ByNameRootBoneMapper byNameRootBoneMapper;
  228. #if UNITY_EDITOR
  229. if (generateAssets) {
  230. byNameRootBoneMapper = (ByNameRootBoneMapper)LoadOrCreateScriptableObject("ByNameRootBoneMapper", "RootBone");
  231. } else {
  232. byNameRootBoneMapper = ScriptableObject.CreateInstance<ByNameRootBoneMapper>();
  233. }
  234. #else
  235. byNameRootBoneMapper = ScriptableObject.CreateInstance<ByNameRootBoneMapper>();
  236. #endif
  237. byNameRootBoneMapper.name = "ByNameRootBoneMapper";
  238. assetLoaderOptions.RootBoneMapper = byNameRootBoneMapper;
  239. if (MaterialMapper.RegisteredMappers.Count == 0)
  240. {
  241. Debug.LogWarning("Please add at least one MaterialMapper name to the MaterialMapper.RegisteredMappers static field to create the right MaterialMapper for the Render Pipeline you are using.");
  242. }
  243. else
  244. {
  245. var materialMappers = new List<MaterialMapper>();
  246. foreach (var materialMapperName in MaterialMapper.RegisteredMappers)
  247. {
  248. if (materialMapperName == null)
  249. {
  250. continue;
  251. }
  252. MaterialMapper materialMapper;
  253. #if UNITY_EDITOR
  254. if (generateAssets)
  255. {
  256. materialMapper = (MaterialMapper)LoadOrCreateScriptableObject(materialMapperName, "Material");
  257. } else {
  258. materialMapper = (MaterialMapper)ScriptableObject.CreateInstance(materialMapperName);
  259. }
  260. #else
  261. materialMapper = ScriptableObject.CreateInstance(materialMapperName) as MaterialMapper;
  262. #endif
  263. if (materialMapper != null)
  264. {
  265. materialMapper.name = materialMapperName;
  266. if (materialMapper.IsCompatible(null))
  267. {
  268. materialMappers.Add(materialMapper);
  269. assetLoaderOptions.FixedAllocations.Add(materialMapper);
  270. }
  271. else
  272. {
  273. #if UNITY_EDITOR
  274. var assetPath = AssetDatabase.GetAssetPath(materialMapper);
  275. if (assetPath == null) {
  276. Object.DestroyImmediate(materialMapper);
  277. }
  278. #else
  279. Object.Destroy(materialMapper);
  280. #endif
  281. }
  282. }
  283. }
  284. if (materialMappers.Count == 0)
  285. {
  286. Debug.LogWarning("TriLib could not find any suitable MaterialMapper on the project.");
  287. }
  288. else
  289. {
  290. assetLoaderOptions.MaterialMappers = materialMappers.ToArray();
  291. }
  292. }
  293. //These two animation clip mappers are used to convert legacy to humanoid animations and add a simple generic animation playback component to the model, which will be disabled by default.
  294. LegacyToHumanoidAnimationClipMapper legacyToHumanoidAnimationClipMapper;
  295. SimpleAnimationPlayerAnimationClipMapper simpleAnimationPlayerAnimationClipMapper;
  296. #if UNITY_EDITOR
  297. if (generateAssets)
  298. {
  299. legacyToHumanoidAnimationClipMapper = (LegacyToHumanoidAnimationClipMapper)LoadOrCreateScriptableObject("LegacyToHumanoidAnimationClipMapper", "AnimationClip");
  300. simpleAnimationPlayerAnimationClipMapper = (SimpleAnimationPlayerAnimationClipMapper)LoadOrCreateScriptableObject("SimpleAnimationPlayerAnimationClipMapper", "AnimationClip");
  301. } else {
  302. legacyToHumanoidAnimationClipMapper = ScriptableObject.CreateInstance<LegacyToHumanoidAnimationClipMapper>();
  303. simpleAnimationPlayerAnimationClipMapper = ScriptableObject.CreateInstance<SimpleAnimationPlayerAnimationClipMapper>();
  304. }
  305. #else
  306. legacyToHumanoidAnimationClipMapper = ScriptableObject.CreateInstance<LegacyToHumanoidAnimationClipMapper>();
  307. simpleAnimationPlayerAnimationClipMapper = ScriptableObject.CreateInstance<SimpleAnimationPlayerAnimationClipMapper>();
  308. #endif
  309. legacyToHumanoidAnimationClipMapper.name = "LegacyToHumanoidAnimationClipMapper";
  310. simpleAnimationPlayerAnimationClipMapper.name = "SimpleAnimationPlayerAnimationClipMapper";
  311. assetLoaderOptions.AnimationClipMappers = new AnimationClipMapper[]
  312. {
  313. legacyToHumanoidAnimationClipMapper,
  314. simpleAnimationPlayerAnimationClipMapper
  315. };
  316. assetLoaderOptions.FixedAllocations.Add(assetLoaderOptions);
  317. assetLoaderOptions.FixedAllocations.Add(legacyToHumanoidAnimationClipMapper);
  318. assetLoaderOptions.FixedAllocations.Add(simpleAnimationPlayerAnimationClipMapper);
  319. return assetLoaderOptions;
  320. }
  321. /// <summary>Processes the Model from the given context and begin to build the Game Objects.</summary>
  322. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param>
  323. private static void ProcessModel(AssetLoaderContext assetLoaderContext)
  324. {
  325. if (assetLoaderContext.RootModel != null)
  326. {
  327. ParseModel(assetLoaderContext, assetLoaderContext.WrapperGameObject != null ? assetLoaderContext.WrapperGameObject.transform : null, assetLoaderContext.RootModel, out assetLoaderContext.RootGameObject);
  328. assetLoaderContext.RootGameObject.transform.localScale = Vector3.one;
  329. if (assetLoaderContext.Options.AnimationType != AnimationType.None || assetLoaderContext.Options.ImportBlendShapes)
  330. {
  331. SetupRootBone(assetLoaderContext);
  332. SetupModelBones(assetLoaderContext, assetLoaderContext.RootModel);
  333. SetupModelLod(assetLoaderContext, assetLoaderContext.RootModel);
  334. BuildGameObjectsPaths(assetLoaderContext);
  335. SetupRig(assetLoaderContext);
  336. }
  337. if (assetLoaderContext.Options.Static)
  338. {
  339. assetLoaderContext.RootGameObject.isStatic = true;
  340. }
  341. }
  342. assetLoaderContext.OnLoad?.Invoke(assetLoaderContext);
  343. assetLoaderContext.ModelsProcessed = true;
  344. }
  345. /// <summary>Configures the context Model LODs (levels-of-detail) if there are any.</summary>
  346. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param>
  347. /// <param name="model">The Model containing the LOD data.</param>
  348. private static void SetupModelLod(AssetLoaderContext assetLoaderContext, IModel model)
  349. {
  350. if (model.Children != null && model.Children.Count > 0)
  351. {
  352. var lodModels = new Dictionary<int, Renderer[]>(model.Children.Count);
  353. var minLod = int.MaxValue;
  354. var maxLod = 0;
  355. foreach (var child in model.Children)
  356. {
  357. var match = Regex.Match(child.Name, "_LOD(?<number>[0-9]+)|LOD_(?<number>[0-9]+)");
  358. if (match.Success)
  359. {
  360. var lodNumber = Convert.ToInt32(match.Groups["number"].Value);
  361. if (lodModels.ContainsKey(lodNumber))
  362. {
  363. continue;
  364. }
  365. minLod = Mathf.Min(lodNumber, minLod);
  366. maxLod = Mathf.Max(lodNumber, maxLod);
  367. lodModels.Add(lodNumber, assetLoaderContext.GameObjects[child].GetComponentsInChildren<Renderer>());
  368. }
  369. }
  370. if (lodModels.Count > 1)
  371. {
  372. var newGameObject = assetLoaderContext.GameObjects[model];
  373. var lods = new LOD[lodModels.Count + 1];
  374. var lodGroup = newGameObject.AddComponent<LODGroup>();
  375. var index = 0;
  376. var lastPosition = 1f;
  377. for (var i = minLod; i <= maxLod; i++)
  378. {
  379. if (lodModels.TryGetValue(i, out var renderers))
  380. {
  381. lods[index++] = new LOD(lastPosition, renderers);
  382. lastPosition *= 0.5f;
  383. }
  384. }
  385. lods[index] = new LOD(lastPosition, null);
  386. lodGroup.SetLODs(lods);
  387. }
  388. }
  389. }
  390. /// <summary>Tries to find the Context Model root-bone.</summary>
  391. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param>
  392. private static void SetupRootBone(AssetLoaderContext assetLoaderContext)
  393. {
  394. var bones = new List<Transform>(assetLoaderContext.Models.Count);
  395. assetLoaderContext.RootModel.GetBones(assetLoaderContext, bones);
  396. assetLoaderContext.BoneTransforms = bones.ToArray();
  397. if (assetLoaderContext.Options.RootBoneMapper != null)
  398. {
  399. assetLoaderContext.RootBone = assetLoaderContext.Options.RootBoneMapper.Map(assetLoaderContext);
  400. }
  401. }
  402. /// <summary>Builds the Game Object Converts hierarchy paths.</summary>
  403. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param>
  404. private static void BuildGameObjectsPaths(AssetLoaderContext assetLoaderContext)
  405. {
  406. foreach (var gameObject in assetLoaderContext.GameObjects.Values)
  407. {
  408. assetLoaderContext.GameObjectPaths.Add(gameObject, gameObject.transform.BuildPath(assetLoaderContext.RootGameObject.transform));
  409. }
  410. }
  411. /// <summary>Configures the context Model rigging if there is any.</summary>
  412. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param>
  413. private static void SetupRig(AssetLoaderContext assetLoaderContext)
  414. {
  415. var animations = assetLoaderContext.RootModel.AllAnimations;
  416. AnimationClip[] animationClips = null;
  417. switch (assetLoaderContext.Options.AnimationType)
  418. {
  419. case AnimationType.Legacy:
  420. {
  421. if (animations != null)
  422. {
  423. animationClips = new AnimationClip[animations.Count];
  424. var unityAnimation = assetLoaderContext.RootGameObject.AddComponent<Animation>();
  425. for (var i = 0; i < animations.Count; i++)
  426. {
  427. var triLibAnimation = animations[i];
  428. var animationClip = ParseAnimation(assetLoaderContext, triLibAnimation);
  429. unityAnimation.AddClip(animationClip, animationClip.name);
  430. unityAnimation.clip = animationClip;
  431. unityAnimation.wrapMode = assetLoaderContext.Options.AnimationWrapMode;
  432. animationClips[i] = animationClip;
  433. }
  434. }
  435. break;
  436. }
  437. case AnimationType.Generic:
  438. {
  439. var animator = assetLoaderContext.RootGameObject.AddComponent<Animator>();
  440. if (assetLoaderContext.Options.AvatarDefinition == AvatarDefinitionType.CopyFromOtherAvatar)
  441. {
  442. animator.avatar = assetLoaderContext.Options.Avatar;
  443. }
  444. else
  445. {
  446. SetupGenericAvatar(assetLoaderContext, animator);
  447. }
  448. if (animations != null)
  449. {
  450. animationClips = new AnimationClip[animations.Count];
  451. for (var i = 0; i < animations.Count; i++)
  452. {
  453. var triLibAnimation = animations[i];
  454. var animationClip = ParseAnimation(assetLoaderContext, triLibAnimation);
  455. animationClips[i] = animationClip;
  456. }
  457. }
  458. break;
  459. }
  460. case AnimationType.Humanoid:
  461. {
  462. var animator = assetLoaderContext.RootGameObject.AddComponent<Animator>();
  463. if (assetLoaderContext.Options.AvatarDefinition == AvatarDefinitionType.CopyFromOtherAvatar)
  464. {
  465. animator.avatar = assetLoaderContext.Options.Avatar;
  466. }
  467. else if (assetLoaderContext.Options.HumanoidAvatarMapper != null)
  468. {
  469. SetupHumanoidAvatar(assetLoaderContext, animator);
  470. }
  471. if (animations != null)
  472. {
  473. animationClips = new AnimationClip[animations.Count];
  474. for (var i = 0; i < animations.Count; i++)
  475. {
  476. var triLibAnimation = animations[i];
  477. var animationClip = ParseAnimation(assetLoaderContext, triLibAnimation);
  478. animationClips[i] = animationClip;
  479. }
  480. }
  481. break;
  482. }
  483. }
  484. if (animationClips != null)
  485. {
  486. if (assetLoaderContext.Options.AnimationClipMappers != null)
  487. {
  488. foreach (var animationClipMapper in assetLoaderContext.Options.AnimationClipMappers)
  489. {
  490. if (animationClipMapper == null)
  491. {
  492. continue;
  493. }
  494. animationClips = animationClipMapper.MapArray(assetLoaderContext, animationClips);
  495. }
  496. }
  497. foreach (var animationClip in animationClips)
  498. {
  499. assetLoaderContext.Allocations.Add(animationClip);
  500. }
  501. }
  502. }
  503. /// <summary>Creates a Skeleton Bone for the given Transform.</summary>
  504. /// <param name="boneTransform">The bone Transform to use on the Skeleton Bone.</param>
  505. /// <returns>The created Skeleton Bone.</returns>
  506. private static SkeletonBone CreateSkeletonBone(Transform boneTransform)
  507. {
  508. var skeletonBone = new SkeletonBone
  509. {
  510. name = boneTransform.name,
  511. position = boneTransform.localPosition,
  512. rotation = boneTransform.localRotation,
  513. scale = boneTransform.localScale
  514. };
  515. return skeletonBone;
  516. }
  517. /// <summary>Creates a Human Bone for the given Bone Mapping, containing the relationship between the Transform and Bone.</summary>
  518. /// <param name="boneMapping">The Bone Mapping used to create the Human Bone, containing the information used to search for bones.</param>
  519. /// <param name="boneName">The bone name to use on the created Human Bone.</param>
  520. /// <returns>The created Human Bone.</returns>
  521. private static HumanBone CreateHumanBone(BoneMapping boneMapping, string boneName)
  522. {
  523. var humanBone = new HumanBone
  524. {
  525. boneName = boneName,
  526. humanName = GetHumanBodyName(boneMapping.HumanBone),
  527. limit =
  528. {
  529. useDefaultValues = boneMapping.HumanLimit.useDefaultValues,
  530. axisLength = boneMapping.HumanLimit.axisLength,
  531. center = boneMapping.HumanLimit.center,
  532. max = boneMapping.HumanLimit.max,
  533. min = boneMapping.HumanLimit.min
  534. }
  535. };
  536. return humanBone;
  537. }
  538. /// <summary>Returns the given Human Body Bones name as String.</summary>
  539. /// <param name="humanBodyBones">The Human Body Bones to get the name from.</param>
  540. /// <returns>The Human Body Bones name.</returns>
  541. private static string GetHumanBodyName(HumanBodyBones humanBodyBones)
  542. {
  543. return HumanTrait.BoneName[(int)humanBodyBones];
  544. }
  545. /// <summary>Creates a Generic Avatar to the given context Model.</summary>
  546. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param>
  547. /// <param name="animator">The Animator assigned to the given Context Root Game Object.</param>
  548. private static void SetupGenericAvatar(AssetLoaderContext assetLoaderContext, Animator animator)
  549. {
  550. var parent = assetLoaderContext.RootGameObject.transform.parent;
  551. assetLoaderContext.RootGameObject.transform.SetParent(null, true);
  552. var avatar = AvatarBuilder.BuildGenericAvatar(assetLoaderContext.RootGameObject, assetLoaderContext.RootBone != null ? assetLoaderContext.RootBone.name : "");
  553. avatar.name = $"{assetLoaderContext.RootGameObject.name}Avatar";
  554. animator.avatar = avatar;
  555. assetLoaderContext.RootGameObject.transform.SetParent(parent, true);
  556. }
  557. /// <summary>Creates a Humanoid Avatar to the given context Model.</summary>
  558. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param>
  559. /// <param name="animator">The Animator assigned to the given Context Root Game Object.</param>
  560. private static void SetupHumanoidAvatar(AssetLoaderContext assetLoaderContext, Animator animator)
  561. {
  562. var index = 0;
  563. var mapping = assetLoaderContext.Options.HumanoidAvatarMapper.Map(assetLoaderContext);
  564. if (mapping.Count > 0)
  565. {
  566. assetLoaderContext.Options.HumanoidAvatarMapper.PostSetup(assetLoaderContext, mapping);
  567. var parent = assetLoaderContext.RootGameObject.transform.parent;
  568. assetLoaderContext.RootGameObject.transform.SetParent(null, true);
  569. var humanBones = new HumanBone[mapping.Count];
  570. foreach (var kvp in mapping)
  571. {
  572. humanBones[index] = CreateHumanBone(kvp.Key, kvp.Value.name);
  573. index++;
  574. }
  575. var skeletonBones = new List<SkeletonBone>(assetLoaderContext.BoneTransforms.Length);
  576. //todo: check if all loaders can get bone information
  577. foreach (var humanBone in humanBones)
  578. {
  579. AddBoneChain(skeletonBones, humanBone.boneName, assetLoaderContext.RootGameObject.transform);
  580. }
  581. HumanDescription humanDescription;
  582. if (assetLoaderContext.Options.HumanDescription == null)
  583. {
  584. humanDescription = new HumanDescription
  585. {
  586. skeleton = skeletonBones.ToArray(),
  587. human = humanBones
  588. };
  589. }
  590. else
  591. {
  592. humanDescription = new HumanDescription
  593. {
  594. armStretch = assetLoaderContext.Options.HumanDescription.armStretch,
  595. feetSpacing = assetLoaderContext.Options.HumanDescription.feetSpacing,
  596. hasTranslationDoF = assetLoaderContext.Options.HumanDescription.hasTranslationDof,
  597. legStretch = assetLoaderContext.Options.HumanDescription.legStretch,
  598. lowerArmTwist = assetLoaderContext.Options.HumanDescription.lowerArmTwist,
  599. lowerLegTwist = assetLoaderContext.Options.HumanDescription.lowerLegTwist,
  600. upperArmTwist = assetLoaderContext.Options.HumanDescription.upperArmTwist,
  601. upperLegTwist = assetLoaderContext.Options.HumanDescription.upperLegTwist,
  602. skeleton = skeletonBones.ToArray(),
  603. human = humanBones
  604. };
  605. }
  606. var avatar = AvatarBuilder.BuildHumanAvatar(assetLoaderContext.RootGameObject, humanDescription);
  607. avatar.name = $"{assetLoaderContext.RootGameObject.name}Avatar";
  608. animator.avatar = avatar;
  609. assetLoaderContext.RootGameObject.transform.SetParent(parent, true);
  610. }
  611. }
  612. /// <summary>Adds a bone to a bone chain.</summary>
  613. /// <param name="skeletonBones">The Skeleton Bones list.</param>
  614. /// <param name="humanBoneBoneName">The Human bone name to search.</param>
  615. /// <param name="rootTransform">The Game Object root Transform.</param>
  616. private static void AddBoneChain(List<SkeletonBone> skeletonBones, string humanBoneBoneName, Transform rootTransform)
  617. {
  618. var transform = rootTransform.FindDeepChild(humanBoneBoneName, StringComparisonMode.RightEqualsLeft, false);
  619. if (transform != null)
  620. {
  621. do
  622. {
  623. var existing = false;
  624. foreach (var skeletonBone in skeletonBones)
  625. {
  626. if (skeletonBone.name == transform.name)
  627. {
  628. existing = true;
  629. break;
  630. }
  631. }
  632. if (!existing)
  633. {
  634. skeletonBones.Add(CreateSkeletonBone(transform));
  635. }
  636. transform = transform.parent;
  637. } while (transform != null);
  638. }
  639. }
  640. /// <summary>Converts the given Model into a Game Object.</summary>
  641. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param>
  642. /// <param name="parentTransform">The parent Game Object Transform.</param>
  643. /// <param name="model">The Model to convert.</param>
  644. /// <param name="newGameObject">The Game Object to receive the converted Model.</param>
  645. private static void ParseModel(AssetLoaderContext assetLoaderContext, Transform parentTransform, IModel model, out GameObject newGameObject)
  646. {
  647. newGameObject = new GameObject(model.Name);
  648. assetLoaderContext.GameObjects.Add(model, newGameObject);
  649. assetLoaderContext.Models.Add(newGameObject, model);
  650. newGameObject.transform.parent = parentTransform;
  651. newGameObject.transform.localPosition = model.LocalPosition;
  652. newGameObject.transform.localRotation = model.LocalRotation;
  653. newGameObject.transform.localScale = model.LocalScale;
  654. if (model.GeometryGroup != null)
  655. {
  656. ParseGeometry(assetLoaderContext, newGameObject, model);
  657. }
  658. if (model.Children != null && model.Children.Count > 0)
  659. {
  660. foreach (var child in model.Children)
  661. {
  662. ParseModel(assetLoaderContext, newGameObject.transform, child, out _);
  663. }
  664. }
  665. }
  666. /// <summary>Configures the given Model skinning if there is any.</summary>
  667. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param>
  668. /// <param name="model">The Model containing the bones.</param>
  669. private static void SetupModelBones(AssetLoaderContext assetLoaderContext, IModel model)
  670. {
  671. var loadedGameObject = assetLoaderContext.GameObjects[model];
  672. var skinnedMeshRenderer = loadedGameObject.GetComponent<SkinnedMeshRenderer>();
  673. if (skinnedMeshRenderer != null)
  674. {
  675. var bones = model.Bones;
  676. if (bones != null && bones.Count > 0)
  677. {
  678. var boneIndex = 0;
  679. var gameObjectBones = new Transform[bones.Count];
  680. foreach (var bone in bones)
  681. {
  682. gameObjectBones[boneIndex++] = assetLoaderContext.GameObjects[bone].transform;
  683. }
  684. skinnedMeshRenderer.bones = gameObjectBones;
  685. skinnedMeshRenderer.rootBone = assetLoaderContext.RootBone;
  686. }
  687. }
  688. if (model.Children != null && model.Children.Count > 0)
  689. {
  690. foreach (var subModel in model.Children)
  691. {
  692. SetupModelBones(assetLoaderContext, subModel);
  693. }
  694. }
  695. }
  696. /// <summary>Converts the given Animation into an Animation Clip.</summary>
  697. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param>
  698. /// <param name="animation">The Animation to convert.</param>
  699. /// <returns>The converted Animation Clip.</returns>
  700. private static AnimationClip ParseAnimation(AssetLoaderContext assetLoaderContext, IAnimation animation)
  701. {
  702. var animationClip = new AnimationClip { name = animation.Name, legacy = assetLoaderContext.Options.AnimationType != AnimationType.Generic, frameRate = animation.FrameRate };
  703. var animationCurveBindings = animation.AnimationCurveBindings;
  704. var rootModel = assetLoaderContext.RootBone != null ? assetLoaderContext.Models[assetLoaderContext.RootBone.gameObject] : null;
  705. foreach (var animationCurveBinding in animationCurveBindings)
  706. {
  707. var animationCurves = animationCurveBinding.AnimationCurves;
  708. var gameObject = assetLoaderContext.GameObjects[animationCurveBinding.Model];
  709. foreach (var animationCurve in animationCurves)
  710. {
  711. var keyFrames = animationCurve.KeyFrames;
  712. var unityAnimationCurve = new AnimationCurve(keyFrames);
  713. var gameObjectPath = assetLoaderContext.GameObjectPaths[gameObject];
  714. var propertyName = animationCurve.Property;
  715. var propertyType = animationCurve.Property.StartsWith("blendShape.") ? typeof(SkinnedMeshRenderer) : typeof(Transform); //todo: refactoring
  716. if (assetLoaderContext.Options.AnimationType == AnimationType.Generic)
  717. {
  718. TryToRemapGenericCurve(rootModel, animationCurve, animationCurveBinding, ref gameObjectPath, ref propertyName, ref propertyType);
  719. }
  720. animationClip.SetCurve(gameObjectPath, propertyType, propertyName, unityAnimationCurve);
  721. }
  722. }
  723. animationClip.EnsureQuaternionContinuity();
  724. return animationClip;
  725. }
  726. /// <summary>Tries to convert a legacy Animation Curve path into a generic Animation path.</summary>
  727. /// <param name="rootBone">The root bone Model.</param>
  728. /// <param name="animationCurve">The Animation Curve Map to remap.</param>
  729. /// <param name="animationCurveBinding">The Animation Curve Binding to remap.</param>
  730. /// <param name="gameObjectPath">The GameObject containing the Curve path.</param>
  731. /// <param name="propertyName">The remapped Property name.</param>
  732. /// <param name="propertyType">The remapped Property type.</param>
  733. private static void TryToRemapGenericCurve(IModel rootBone, IAnimationCurve animationCurve, IAnimationCurveBinding animationCurveBinding, ref string gameObjectPath, ref string propertyName, ref Type propertyType)
  734. {
  735. if (animationCurveBinding.Model == rootBone)
  736. {
  737. var remap = false;
  738. switch (animationCurve.Property)
  739. {
  740. case Constants.LocalPositionXProperty:
  741. propertyName = Constants.RootPositionXProperty;
  742. remap = true;
  743. break;
  744. case Constants.LocalPositionYProperty:
  745. propertyName = Constants.RootPositionYProperty;
  746. remap = true;
  747. break;
  748. case Constants.LocalPositionZProperty:
  749. propertyName = Constants.RootPositionZProperty;
  750. remap = true;
  751. break;
  752. case Constants.LocalRotationXProperty:
  753. propertyName = Constants.RootRotationXProperty;
  754. remap = true;
  755. break;
  756. case Constants.LocalRotationYProperty:
  757. propertyName = Constants.RootRotationYProperty;
  758. remap = true;
  759. break;
  760. case Constants.LocalRotationZProperty:
  761. propertyName = Constants.RootRotationZProperty;
  762. remap = true;
  763. break;
  764. case Constants.LocalRotationWProperty:
  765. propertyName = Constants.RootRotationWProperty;
  766. remap = true;
  767. break;
  768. }
  769. if (remap)
  770. {
  771. gameObjectPath = "";
  772. propertyType = typeof(Animator);
  773. }
  774. }
  775. }
  776. /// <summary>Converts the given Geometry Group into a Mesh.</summary>
  777. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param>
  778. /// <param name="meshGameObject">The Game Object where the Mesh belongs.</param>
  779. /// <param name="meshModel">The Model used to generate the Game Object.</param>
  780. private static void ParseGeometry(AssetLoaderContext assetLoaderContext, GameObject meshGameObject, IModel meshModel)
  781. {
  782. var geometryGroup = meshModel.GeometryGroup;
  783. var geometries = geometryGroup.Geometries;
  784. var mesh = new Mesh { name = geometryGroup.Name, subMeshCount = geometries?.Count ?? 0, indexFormat = assetLoaderContext.Options.IndexFormat };
  785. assetLoaderContext.Allocations.Add(mesh);
  786. if (geometries != null)
  787. {
  788. if (assetLoaderContext.Options.ReadAndWriteEnabled)
  789. {
  790. mesh.MarkDynamic();
  791. }
  792. if (assetLoaderContext.Options.LipSyncMappers != null)
  793. {
  794. foreach (var lipSyncMapper in assetLoaderContext.Options.LipSyncMappers)
  795. {
  796. if (lipSyncMapper == null)
  797. {
  798. continue;
  799. }
  800. if (lipSyncMapper.Map(assetLoaderContext, geometryGroup, out var visemeToBlendTargets))
  801. {
  802. var lipSyncMapping = meshGameObject.AddComponent<LipSyncMapping>();
  803. lipSyncMapping.VisemeToBlendTargets = visemeToBlendTargets;
  804. break;
  805. }
  806. }
  807. }
  808. geometries = mesh.CombineGeometries(geometryGroup, meshModel.BindPoses, assetLoaderContext);
  809. if (assetLoaderContext.Options.GenerateColliders)
  810. {
  811. if (assetLoaderContext.RootModel.AllAnimations != null && assetLoaderContext.RootModel.AllAnimations.Count > 0)
  812. {
  813. if (assetLoaderContext.Options.ShowLoadingWarnings)
  814. {
  815. Debug.LogWarning("Trying to add a MeshCollider to an animated object.");
  816. }
  817. }
  818. else
  819. {
  820. var meshCollider = meshGameObject.AddComponent<MeshCollider>();
  821. meshCollider.sharedMesh = mesh;
  822. meshCollider.convex = assetLoaderContext.Options.ConvexColliders;
  823. }
  824. }
  825. var allMaterials = new IMaterial[geometries.Count];
  826. var modelMaterials = meshModel.Materials;
  827. if (modelMaterials != null)
  828. {
  829. for (var i = 0; i < geometries.Count; i++)
  830. {
  831. var geometry = geometries[i];
  832. allMaterials[i] = modelMaterials[Mathf.Clamp(geometry.MaterialIndex, 0, meshModel.Materials.Count - 1)];
  833. }
  834. }
  835. Renderer renderer = null;
  836. if (assetLoaderContext.Options.AnimationType != AnimationType.None || assetLoaderContext.Options.ImportBlendShapes)
  837. {
  838. var bones = meshModel.Bones;
  839. var geometryGroupBlendShapeGeometryBindings = geometryGroup.BlendShapeGeometryBindings;
  840. if (bones != null && bones.Count > 0 || geometryGroupBlendShapeGeometryBindings != null && geometryGroupBlendShapeGeometryBindings.Count > 0)
  841. {
  842. var skinnedMeshRenderer = meshGameObject.AddComponent<SkinnedMeshRenderer>();
  843. skinnedMeshRenderer.sharedMesh = mesh;
  844. skinnedMeshRenderer.enabled = !assetLoaderContext.Options.ImportVisibility || meshModel.Visibility;
  845. renderer = skinnedMeshRenderer;
  846. }
  847. }
  848. if (renderer == null)
  849. {
  850. var meshFilter = meshGameObject.AddComponent<MeshFilter>();
  851. meshFilter.sharedMesh = mesh;
  852. var meshRenderer = meshGameObject.AddComponent<MeshRenderer>();
  853. meshRenderer.enabled = !assetLoaderContext.Options.ImportVisibility || meshModel.Visibility;
  854. renderer = meshRenderer;
  855. }
  856. var materials = new Material[allMaterials.Length];
  857. Material loadingMaterial = null;
  858. foreach (var mapper in assetLoaderContext.Options.MaterialMappers)
  859. {
  860. if (mapper != null && mapper.IsCompatible(null))
  861. {
  862. loadingMaterial = mapper.LoadingMaterial;
  863. break;
  864. }
  865. }
  866. if (loadingMaterial == null)
  867. {
  868. if (assetLoaderContext.Options.ShowLoadingWarnings)
  869. {
  870. Debug.LogWarning("Could not find a suitable loading Material");
  871. }
  872. }
  873. else
  874. {
  875. for (var i = 0; i < materials.Length; i++)
  876. {
  877. materials[i] = loadingMaterial;
  878. }
  879. }
  880. renderer.sharedMaterials = materials;
  881. for (var i = 0; i < allMaterials.Length; i++)
  882. {
  883. var sourceMaterial = allMaterials[i];
  884. if (sourceMaterial == null)
  885. {
  886. continue;
  887. }
  888. var materialRenderersContext = new MaterialRendererContext
  889. {
  890. Context = assetLoaderContext,
  891. Renderer = renderer,
  892. MaterialIndex = i,
  893. Material = sourceMaterial
  894. };
  895. if (assetLoaderContext.MaterialRenderers.TryGetValue(sourceMaterial, out var materialRendererContextList))
  896. {
  897. materialRendererContextList.Add(materialRenderersContext);
  898. }
  899. else
  900. {
  901. assetLoaderContext.MaterialRenderers.Add(sourceMaterial, new List<MaterialRendererContext> { materialRenderersContext });
  902. }
  903. }
  904. }
  905. }
  906. /// <summary>Loads the root Model.</summary>
  907. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param>
  908. private static void LoadModel(AssetLoaderContext assetLoaderContext)
  909. {
  910. if (assetLoaderContext.Options.MaterialMappers != null)
  911. {
  912. Array.Sort(assetLoaderContext.Options.MaterialMappers, (a, b) => a.CheckingOrder > b.CheckingOrder ? -1 : 1);
  913. }
  914. else if (assetLoaderContext.Options.ShowLoadingWarnings)
  915. {
  916. Debug.LogWarning("Your AssetLoaderOptions instance has no MaterialMappers. TriLib can't process materials without them.");
  917. }
  918. #if TRILIB_DRACO
  919. GltfReader.DracoDecompressorCallback = DracoMeshLoader.DracoDecompressorCallback;
  920. #endif
  921. var fileExtension = assetLoaderContext.FileExtension ?? FileUtils.GetFileExtension(assetLoaderContext.Filename, false).ToLowerInvariant();
  922. if (assetLoaderContext.Stream == null)
  923. {
  924. var fileStream = new FileStream(assetLoaderContext.Filename, FileMode.Open);
  925. assetLoaderContext.Stream = fileStream;
  926. var reader = Readers.FindReaderForExtension(fileExtension);
  927. if (reader != null)
  928. {
  929. assetLoaderContext.RootModel = reader.ReadStream(fileStream, assetLoaderContext, assetLoaderContext.Filename, assetLoaderContext.OnProgress);
  930. }
  931. }
  932. else
  933. {
  934. var reader = Readers.FindReaderForExtension(fileExtension);
  935. if (reader != null)
  936. {
  937. assetLoaderContext.RootModel = reader.ReadStream(assetLoaderContext.Stream, assetLoaderContext, null, assetLoaderContext.OnProgress);
  938. }
  939. }
  940. }
  941. /// <summary>Processes the root Model.</summary>
  942. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the information used during the Model loading process, which is available to almost every Model processing method</param>
  943. private static void ProcessRootModel(AssetLoaderContext assetLoaderContext)
  944. {
  945. ProcessModel(assetLoaderContext);
  946. if (assetLoaderContext.Async)
  947. {
  948. ThreadUtils.RunThread(assetLoaderContext, ref assetLoaderContext.CancellationToken, ProcessTextures, null, assetLoaderContext.HandleError ?? assetLoaderContext.OnError, assetLoaderContext.Options.Timeout);
  949. }
  950. else
  951. {
  952. ProcessTextures(assetLoaderContext);
  953. }
  954. }
  955. private static void TryProcessMaterials(AssetLoaderContext assetLoaderContext)
  956. {
  957. var allMaterialsLoaded = assetLoaderContext.RootModel?.AllTextures == null || assetLoaderContext.LoadedTexturesCount == assetLoaderContext.RootModel.AllTextures.Count;
  958. if (!assetLoaderContext.MaterialsProcessed && allMaterialsLoaded)
  959. {
  960. assetLoaderContext.MaterialsProcessed = true;
  961. if (assetLoaderContext.RootModel?.AllMaterials != null)
  962. {
  963. ProcessMaterials(assetLoaderContext);
  964. }
  965. if (assetLoaderContext.Options.AddAssetUnloader && assetLoaderContext.RootGameObject != null || assetLoaderContext.WrapperGameObject != null)
  966. {
  967. var gameObject = assetLoaderContext.RootGameObject ?? assetLoaderContext.WrapperGameObject;
  968. var assetUnloader = gameObject.AddComponent<AssetUnloader>();
  969. assetUnloader.Id = AssetUnloader.GetNextId();
  970. assetUnloader.Allocations = assetLoaderContext.Allocations;
  971. }
  972. assetLoaderContext.OnMaterialsLoad?.Invoke(assetLoaderContext);
  973. TryToCloseStream(assetLoaderContext);
  974. }
  975. }
  976. private static void ProcessTextures(AssetLoaderContext assetLoaderContext)
  977. {
  978. if (assetLoaderContext.RootModel?.AllTextures != null)
  979. {
  980. for (var i = 0; i < assetLoaderContext.RootModel.AllTextures.Count; i++)
  981. {
  982. var texture = assetLoaderContext.RootModel.AllTextures[i];
  983. TextureLoadingContext textureLoadingContext = null;
  984. if (assetLoaderContext.Options.TextureMapper != null)
  985. {
  986. textureLoadingContext = assetLoaderContext.Options.TextureMapper.Map(assetLoaderContext, texture);
  987. }
  988. if (textureLoadingContext == null)
  989. {
  990. textureLoadingContext = new TextureLoadingContext
  991. {
  992. Context = assetLoaderContext,
  993. Texture = texture
  994. };
  995. }
  996. StbImage.LoadTexture(textureLoadingContext);
  997. assetLoaderContext.Reader.UpdateLoadingPercentage((float)i / assetLoaderContext.RootModel.AllTextures.Count, 1);
  998. }
  999. }
  1000. assetLoaderContext.Reader.UpdateLoadingPercentage(1f, 1);
  1001. if (assetLoaderContext.Async)
  1002. {
  1003. Dispatcher.InvokeAsync(new ContextualizedAction<AssetLoaderContext>(TryProcessMaterials, assetLoaderContext));
  1004. }
  1005. else
  1006. {
  1007. TryProcessMaterials(assetLoaderContext);
  1008. }
  1009. }
  1010. private static void ProcessMaterials(AssetLoaderContext assetLoaderContext)
  1011. {
  1012. if (assetLoaderContext.Options.MaterialMappers != null)
  1013. {
  1014. foreach (var material in assetLoaderContext.RootModel.AllMaterials)
  1015. {
  1016. MaterialMapper usedMaterialMapper = null;
  1017. var materialMapperContext = new MaterialMapperContext
  1018. {
  1019. Context = assetLoaderContext,
  1020. Material = material
  1021. };
  1022. foreach (var materialMapper in assetLoaderContext.Options.MaterialMappers)
  1023. {
  1024. if (materialMapper == null || !materialMapper.IsCompatible(materialMapperContext))
  1025. {
  1026. continue;
  1027. }
  1028. materialMapper.Map(materialMapperContext);
  1029. usedMaterialMapper = materialMapper;
  1030. break;
  1031. }
  1032. if (usedMaterialMapper != null)
  1033. {
  1034. if (assetLoaderContext.MaterialRenderers.TryGetValue(material, out var materialRendererList))
  1035. {
  1036. foreach (var materialRendererContext in materialRendererList)
  1037. {
  1038. usedMaterialMapper.ApplyMaterialToRenderer(materialRendererContext, materialMapperContext);
  1039. }
  1040. }
  1041. }
  1042. }
  1043. }
  1044. else if (assetLoaderContext.Options.ShowLoadingWarnings)
  1045. {
  1046. Debug.LogWarning("The given AssetLoaderOptions contains no MaterialMapper. Materials will not be created.");
  1047. }
  1048. }
  1049. /// <summary>Handles all Model loading errors, unloads the partially loaded Model (if suitable), and calls the error callback (if existing).</summary>
  1050. /// <param name="error">The Contextualized Error that has occurred.</param>
  1051. private static void HandleError(IContextualizedError error)
  1052. {
  1053. var exception = error.GetInnerException();
  1054. if (error.GetContext() is IAssetLoaderContext iassetLoaderContext)
  1055. {
  1056. var assetLoaderContext = iassetLoaderContext.Context;
  1057. if (assetLoaderContext != null)
  1058. {
  1059. TryToCloseStream(assetLoaderContext);
  1060. if (assetLoaderContext.Options.DestroyOnError && assetLoaderContext.RootGameObject != null)
  1061. {
  1062. #if UNITY_EDITOR
  1063. Object.DestroyImmediate(assetLoaderContext.RootGameObject);
  1064. #else
  1065. Object.Destroy(assetLoaderContext.RootGameObject);
  1066. #endif
  1067. assetLoaderContext.RootGameObject = null;
  1068. }
  1069. if (assetLoaderContext.Async)
  1070. {
  1071. Dispatcher.InvokeAsync(new ContextualizedAction<IContextualizedError>(assetLoaderContext.OnError, error));
  1072. }
  1073. else if (assetLoaderContext.OnError != null)
  1074. {
  1075. assetLoaderContext.OnError(error);
  1076. }
  1077. }
  1078. }
  1079. else
  1080. {
  1081. var contextualizedAction = new ContextualizedAction<ContextualizedError<object>>(Rethrow, new ContextualizedError<object>(exception, null));
  1082. Dispatcher.InvokeAsync(contextualizedAction);
  1083. }
  1084. }
  1085. private static void TryToCloseStream(AssetLoaderContext assetLoaderContext)
  1086. {
  1087. if (assetLoaderContext.Stream != null && assetLoaderContext.Options.CloseStreamAutomatically)
  1088. {
  1089. try
  1090. {
  1091. assetLoaderContext.Stream.Dispose();
  1092. }
  1093. catch (Exception e)
  1094. {
  1095. }
  1096. }
  1097. }
  1098. /// <summary>Throws the given Contextualized Error on the main Thread.</summary>
  1099. /// <typeparam name="T"></typeparam>
  1100. /// <param name="contextualizedError">The Contextualized Error to throw.</param>
  1101. private static void Rethrow<T>(ContextualizedError<T> contextualizedError)
  1102. {
  1103. throw contextualizedError;
  1104. }
  1105. }
  1106. }