AssetLoader.cs 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421
  1. #pragma warning disable 168, 618
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text.RegularExpressions;
  7. using TriLibCore.Extensions;
  8. using TriLibCore.General;
  9. using TriLibCore.Interfaces;
  10. using TriLibCore.Mappers;
  11. using TriLibCore.Textures;
  12. using TriLibCore.Utils;
  13. using UnityEngine;
  14. using FileMode = System.IO.FileMode;
  15. using HumanDescription = UnityEngine.HumanDescription;
  16. using Object = UnityEngine.Object;
  17. using TriLibCore.Attributes;
  18. using TriLibCore.Collections;
  19. using TriLibCore.Geometries;
  20. using Unity.Collections;
  21. using Unity.Collections.LowLevel.Unsafe;
  22. #if TRILIB_DRACO
  23. using TriLibCore.Gltf.Reader;
  24. using TriLibCore.Gltf.Draco;
  25. #endif
  26. #if UNITY_EDITOR
  27. using UnityEditor;
  28. #endif
  29. namespace TriLibCore
  30. {
  31. /// <summary>Represents the main class containing methods to load the Models.</summary>
  32. public static partial class AssetLoader
  33. {
  34. /// <summary>
  35. /// Asset Loader Options validation message.
  36. /// </summary>
  37. private const string ValidationMessage = "You can disable these validations in the Edit->Project Settings->TriLib menu.";
  38. /// <summary>
  39. /// Constant that defines the namespace used by TriLib Mappers.
  40. /// </summary>
  41. private const string TriLibMappersNamespace = "TriLibCore.Mappers";
  42. /// <summary>Loads a Model from the given path asynchronously.</summary>
  43. /// <param name="path">The Model file path.</param>
  44. /// <param name="onLoad">The Method to call on the Main Thread when the Model is loaded but resources may still pending.</param>
  45. /// <param name="onMaterialsLoad">The Method to call on the Main Thread when the Model and resources are loaded.</param>
  46. /// <param name="onProgress">The Method to call when the Model loading progress changes.</param>
  47. /// <param name="onError">The Method to call on the Main Thread when any error occurs.</param>
  48. /// <param name="wrapperGameObject">The Game Object that will be the parent of the loaded Game Object. Can be null.</param>
  49. /// <param name="assetLoaderOptions">The options to use when loading the Model.</param>
  50. /// <param name="customContextData">The Custom Data that will be passed along the Context.</param>
  51. /// <param name="haltTask">Turn on this field to avoid loading the model immediately and chain the Tasks.</param>
  52. /// <param name="onPreLoad">The method to call on the parallel Thread before the Unity objects are created.</param>
  53. /// <param name="isZipFile">Indicates whether to load from a Zip file.</param>
  54. /// <returns>The Asset Loader Context, containing Model loading information and the output Game Object.</returns>
  55. public static AssetLoaderContext LoadModelFromFile(string path,
  56. Action<AssetLoaderContext> onLoad = null,
  57. Action<AssetLoaderContext> onMaterialsLoad = null,
  58. Action<AssetLoaderContext, float> onProgress = null,
  59. Action<IContextualizedError> onError = null,
  60. GameObject wrapperGameObject = null,
  61. AssetLoaderOptions assetLoaderOptions = null,
  62. object customContextData = null,
  63. bool haltTask = false,
  64. Action<AssetLoaderContext> onPreLoad = null,
  65. bool isZipFile = false)
  66. {
  67. var assetLoaderContext = new AssetLoaderContext
  68. {
  69. Options = assetLoaderOptions ?? CreateDefaultLoaderOptions(),
  70. Filename = path,
  71. BasePath = FileUtils.GetFileDirectory(path),
  72. WrapperGameObject = wrapperGameObject,
  73. OnMaterialsLoad = onMaterialsLoad,
  74. OnLoad = onLoad,
  75. OnProgress = onProgress,
  76. HandleError = HandleError,
  77. OnError = onError,
  78. OnPreLoad = onPreLoad,
  79. CustomData = customContextData,
  80. HaltTasks = haltTask,
  81. #if (UNITY_WEBGL && !TRILIB_ENABLE_WEBGL_THREADS) || (UNITY_WSA && !TRILIB_ENABLE_UWP_THREADS) || TRILIB_FORCE_SYNC
  82. Async = false,
  83. #else
  84. Async = true,
  85. #endif
  86. IsZipFile = isZipFile,
  87. PersistentDataPath = Application.persistentDataPath
  88. };
  89. LoadModelInternal(assetLoaderContext);
  90. return assetLoaderContext;
  91. }
  92. /// <summary>Loads a Model from the given Stream asynchronously.</summary>
  93. /// <param name="stream">The Stream containing the Model data.</param>
  94. /// <param name="filename">The Model filename.</param>
  95. /// <param name="fileExtension">The Model file extension. (Eg.: fbx)</param>
  96. /// <param name="onLoad">The Method to call on the Main Thread when the Model is loaded but resources may still pending.</param>
  97. /// <param name="onMaterialsLoad">The Method to call on the Main Thread when the Model and resources are loaded.</param>
  98. /// <param name="onProgress">The Method to call when the Model loading progress changes.</param>
  99. /// <param name="onError">The Method to call on the Main Thread when any error occurs.</param>
  100. /// <param name="wrapperGameObject">The Game Object that will be the parent of the loaded Game Object. Can be null.</param>
  101. /// <param name="assetLoaderOptions">The options to use when loading the Model.</param>
  102. /// <param name="customContextData">The Custom Data that will be passed along the Context.</param>
  103. /// <param name="haltTask">Turn on this field to avoid loading the model immediately and chain the Tasks.</param>
  104. /// <param name="onPreLoad">The method to call on the parallel Thread before the Unity objects are created.</param>
  105. /// <param name="isZipFile">Indicates whether to load from a Zip file.</param>
  106. /// <returns>The Asset Loader Context, containing Model loading information and the output Game Object.</returns>
  107. public static AssetLoaderContext LoadModelFromStream(Stream stream,
  108. string filename = null,
  109. string fileExtension = null,
  110. Action<AssetLoaderContext> onLoad = null,
  111. Action<AssetLoaderContext> onMaterialsLoad = null,
  112. Action<AssetLoaderContext, float> onProgress = null,
  113. Action<IContextualizedError> onError = null,
  114. GameObject wrapperGameObject = null,
  115. AssetLoaderOptions assetLoaderOptions = null,
  116. object customContextData = null,
  117. bool haltTask = false,
  118. Action<AssetLoaderContext> onPreLoad = null,
  119. bool isZipFile = false)
  120. {
  121. var assetLoaderContext = new AssetLoaderContext
  122. {
  123. Options = assetLoaderOptions ?? CreateDefaultLoaderOptions(),
  124. Stream = stream,
  125. Filename = filename,
  126. FileExtension = fileExtension ?? FileUtils.GetFileExtension(filename, false),
  127. BasePath = FileUtils.GetFileDirectory(filename),
  128. WrapperGameObject = wrapperGameObject,
  129. OnMaterialsLoad = onMaterialsLoad,
  130. OnLoad = onLoad,
  131. OnProgress = onProgress,
  132. HandleError = HandleError,
  133. OnError = onError,
  134. OnPreLoad = onPreLoad,
  135. CustomData = customContextData,
  136. HaltTasks = haltTask,
  137. #if (UNITY_WEBGL && !TRILIB_ENABLE_WEBGL_THREADS) || (UNITY_WSA && !TRILIB_ENABLE_UWP_THREADS) || TRILIB_FORCE_SYNC
  138. Async = false,
  139. #else
  140. Async = true,
  141. #endif
  142. IsZipFile = isZipFile,
  143. PersistentDataPath = Application.persistentDataPath
  144. };
  145. LoadModelInternal(assetLoaderContext);
  146. return assetLoaderContext;
  147. }
  148. /// <summary>Loads a Model from the given path synchronously.</summary>
  149. /// <param name="path">The Model file path.</param>
  150. /// <param name="onError">The Method to call on the Main Thread when any error occurs.</param>
  151. /// <param name="wrapperGameObject">The Game Object that will be the parent of the loaded Game Object. Can be null.</param>
  152. /// <param name="assetLoaderOptions">The options to use when loading the Model.</param>
  153. /// <param name="customContextData">The Custom Data that will be passed along the Context.</param>
  154. /// <param name="isZipFile">Indicates whether to load from a Zip file.</param>
  155. /// <returns>The Asset Loader Context, containing Model loading information and the output Game Object.</returns>
  156. public static AssetLoaderContext LoadModelFromFileNoThread(string path,
  157. Action<IContextualizedError> onError = null,
  158. GameObject wrapperGameObject = null,
  159. AssetLoaderOptions assetLoaderOptions = null,
  160. object customContextData = null,
  161. bool isZipFile = false)
  162. {
  163. var assetLoaderContext = new AssetLoaderContext
  164. {
  165. Options = assetLoaderOptions ?? CreateDefaultLoaderOptions(),
  166. Filename = path,
  167. BasePath = FileUtils.GetFileDirectory(path),
  168. CustomData = customContextData,
  169. HandleError = HandleError,
  170. OnError = onError,
  171. WrapperGameObject = wrapperGameObject,
  172. Async = false,
  173. IsZipFile = isZipFile,
  174. PersistentDataPath = Application.persistentDataPath
  175. };
  176. LoadModelInternal(assetLoaderContext);
  177. return assetLoaderContext;
  178. }
  179. /// <summary>Loads a Model from the given Stream synchronously.</summary>
  180. /// <param name="stream">The Stream containing the Model data.</param>
  181. /// <param name="filename">The Model filename.</param>
  182. /// <param name="fileExtension">The Model file extension. (Eg.: fbx)</param>
  183. /// <param name="onError">The Method to call on the Main Thread when any error occurs.</param>
  184. /// <param name="wrapperGameObject">The Game Object that will be the parent of the loaded Game Object. Can be null.</param>
  185. /// <param name="assetLoaderOptions">The options to use when loading the Model.</param>
  186. /// <param name="customContextData">The Custom Data that will be passed along the Context.</param>
  187. /// <param name="isZipFile">Indicates whether to load from a Zip file.</param>
  188. /// <returns>The Asset Loader Context, containing Model loading information and the output Game Object.</returns>
  189. public static AssetLoaderContext LoadModelFromStreamNoThread(Stream stream,
  190. string filename = null,
  191. string fileExtension = null,
  192. Action<IContextualizedError> onError = null,
  193. GameObject wrapperGameObject = null,
  194. AssetLoaderOptions assetLoaderOptions = null,
  195. object customContextData = null,
  196. bool isZipFile = false)
  197. {
  198. var assetLoaderContext = new AssetLoaderContext
  199. {
  200. Options = assetLoaderOptions ?? CreateDefaultLoaderOptions(),
  201. Stream = stream,
  202. Filename = filename,
  203. FileExtension = fileExtension ?? FileUtils.GetFileExtension(filename, false),
  204. BasePath = FileUtils.GetFileDirectory(filename),
  205. CustomData = customContextData,
  206. HandleError = HandleError,
  207. OnError = onError,
  208. WrapperGameObject = wrapperGameObject,
  209. Async = false,
  210. IsZipFile = isZipFile,
  211. PersistentDataPath = Application.persistentDataPath
  212. };
  213. LoadModelInternal(assetLoaderContext);
  214. return assetLoaderContext;
  215. }
  216. /// <summary>Begins the model loading process.</summary>
  217. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  218. private static void LoadModelInternal(AssetLoaderContext assetLoaderContext)
  219. {
  220. SetupCallbacks();
  221. #if !TRILIB_DISABLE_VALIDATIONS
  222. ValidateAssetLoaderOptions(assetLoaderContext.Options);
  223. #endif
  224. #if TRILIB_USE_THREAD_NAMES && !UNITY_WSA
  225. var threadName = "TriLib_LoadModelFromStream";
  226. #else
  227. string threadName = null;
  228. #endif
  229. var fileExtension = assetLoaderContext.FileExtension;
  230. if (fileExtension == null && assetLoaderContext.Filename != null)
  231. {
  232. fileExtension = FileUtils.GetFileExtension(assetLoaderContext.Filename, false);
  233. }
  234. if (fileExtension == "zip")
  235. {
  236. AssetLoaderZip.LoadModelFromZipFile(assetLoaderContext.Filename,
  237. assetLoaderContext.OnLoad,
  238. assetLoaderContext.OnMaterialsLoad,
  239. assetLoaderContext.OnProgress,
  240. assetLoaderContext.OnError,
  241. assetLoaderContext.WrapperGameObject,
  242. assetLoaderContext.Options,
  243. assetLoaderContext.CustomData,
  244. assetLoaderContext.FileExtension,
  245. assetLoaderContext.HaltTasks,
  246. assetLoaderContext.OnPreLoad);
  247. }
  248. else
  249. {
  250. ThreadUtils.RequestNewThreadFor(
  251. assetLoaderContext,
  252. LoadModel,
  253. ProcessRootModel,
  254. HandleError,
  255. assetLoaderContext.Options.Timeout,
  256. threadName,
  257. !assetLoaderContext.HaltTasks,
  258. assetLoaderContext.OnPreLoad
  259. );
  260. }
  261. }
  262. /// <summary>
  263. /// Configures callbacks.
  264. /// </summary>
  265. private static void SetupCallbacks()
  266. {
  267. Texture.allowThreadedTextureCreation = true;
  268. MaterialMapper.CreateTextureCallback = TextureLoaders.CreateTexture;
  269. MaterialMapper.ScanForAlphaPixelsCallback = TextureLoaders.ScanForAlphaPixels;
  270. MaterialMapper.LoadTextureCallback = TextureLoaders.LoadTexture;
  271. MaterialMapper.PostProcessTextureCallback = TextureLoaders.PostProcessTexture;
  272. MaterialMapper.ApplyTextureCallback = TextureUtils.ApplyTexture2D;
  273. MaterialMapper.FixNPOTTextureCallback = TextureUtils.FixNPOTTexture;
  274. MaterialMapper.FixNormalMapCallback = TextureUtils.FixNormalMap;
  275. }
  276. /// <summary>
  277. /// Validates the given AssetLoaderOptions.
  278. /// </summary>
  279. /// <param name="assetLoaderOptions">The options to use when loading the Model.</param>
  280. private static void ValidateAssetLoaderOptions(AssetLoaderOptions assetLoaderOptions)
  281. {
  282. #if ENABLE_IL2CPP
  283. if (assetLoaderOptions.EnableProfiler) {
  284. assetLoaderOptions.EnableProfiler = false;
  285. Debug.LogWarning("TriLib: The built in profiler has been disabled as it does not work with IL2CPP builds.");
  286. Debug.LogWarning(ValidationMessage);
  287. }
  288. #endif
  289. if (GraphicsSettingsUtils.IsUsingUniversalPipeline && assetLoaderOptions.LoadTexturesAsSRGB)
  290. {
  291. Debug.LogWarning("TriLib: Textures must be loaded as Linear on the UniversalRP.");
  292. Debug.LogWarning(ValidationMessage);
  293. assetLoaderOptions.LoadTexturesAsSRGB = false;
  294. }
  295. }
  296. #if UNITY_EDITOR
  297. private static Object LoadOrCreateScriptableObject(string type, string @namespace, string subFolder)
  298. {
  299. string mappersFilePath;
  300. var triLibMapperAssets = AssetDatabase.FindAssets("TriLibMappersPlaceholder");
  301. if (triLibMapperAssets.Length > 0)
  302. {
  303. mappersFilePath = AssetDatabase.GUIDToAssetPath(triLibMapperAssets[0]);
  304. }
  305. else
  306. {
  307. throw new Exception("Could not find \"TriLibMappersPlaceholder\" file. Please re-import TriLib package.");
  308. }
  309. var mappersDirectory = $"{FileUtils.GetFileDirectory(mappersFilePath)}";
  310. var assetDirectory = $"{mappersDirectory}/{subFolder}";
  311. if (!AssetDatabase.IsValidFolder(assetDirectory))
  312. {
  313. AssetDatabase.CreateFolder(mappersDirectory, subFolder);
  314. }
  315. var assetPath = $"{assetDirectory}/{type}.asset";
  316. var scriptableObject = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Object));
  317. if (scriptableObject == null)
  318. {
  319. scriptableObject = CreateScriptableObjectSafe(type, @namespace);
  320. if (scriptableObject != null)
  321. {
  322. AssetDatabase.CreateAsset(scriptableObject, assetPath);
  323. }
  324. }
  325. return scriptableObject;
  326. }
  327. #endif
  328. /// <summary>Creates an Asset Loader Options with the default settings and Mappers.</summary>
  329. /// <param name="generateAssets">Indicates whether created Scriptable Objects will be saved as assets.</param>
  330. /// <param name="supressWarning">Pass `true `if you are caching your AssetLoaderOptions instance.</param>
  331. /// <returns>The Asset Loader Options containing the default settings.</returns>
  332. public static AssetLoaderOptions CreateDefaultLoaderOptions(bool generateAssets = false, bool supressWarning = false)
  333. {
  334. if (!supressWarning)
  335. {
  336. Debug.LogWarning("TriLib: You are creating a new AssetLoaderOptions instance. If you are caching this instance and don't want this message to be displayed again, pass `false` to the `supressWarning` parameter of `CreateDefaultLoaderOptions` call.");
  337. }
  338. var assetLoaderOptions = ScriptableObject.CreateInstance<AssetLoaderOptions>();
  339. ByBonesRootBoneMapper byBonesRootBoneMapper;
  340. #if UNITY_EDITOR
  341. if (generateAssets)
  342. {
  343. byBonesRootBoneMapper = (ByBonesRootBoneMapper)LoadOrCreateScriptableObject("ByBonesRootBoneMapper", TriLibMappersNamespace, "RootBone");
  344. }
  345. else
  346. {
  347. byBonesRootBoneMapper = ScriptableObject.CreateInstance<ByBonesRootBoneMapper>();
  348. }
  349. #else
  350. byBonesRootBoneMapper = ScriptableObject.CreateInstance<ByBonesRootBoneMapper>();
  351. #endif
  352. byBonesRootBoneMapper.name = "ByBonesRootBoneMapper";
  353. assetLoaderOptions.RootBoneMapper = byBonesRootBoneMapper;
  354. var materialMappers = new List<MaterialMapper>();
  355. for (var i = 0; i < MaterialMapper.RegisteredMappers.Count; i++)
  356. {
  357. var materialMapperName = MaterialMapper.RegisteredMappers[i];
  358. var materialMapperNamespace = MaterialMapper.RegisteredMapperNamespaces[i];
  359. if (materialMapperName == null)
  360. {
  361. continue;
  362. }
  363. MaterialMapper materialMapper;
  364. try
  365. {
  366. #if UNITY_EDITOR
  367. if (generateAssets)
  368. {
  369. materialMapper = LoadOrCreateScriptableObject(materialMapperName, materialMapperNamespace, "Material") as MaterialMapper;
  370. }
  371. else
  372. {
  373. materialMapper = CreateScriptableObjectSafe(materialMapperName, materialMapperNamespace) as MaterialMapper;
  374. }
  375. #else
  376. materialMapper = CreateScriptableObjectSafe(materialMapperName, materialMapperNamespace) as MaterialMapper;
  377. #endif
  378. }
  379. catch
  380. {
  381. materialMapper = null;
  382. }
  383. if (materialMapper is object)
  384. {
  385. materialMapper.name = materialMapperName;
  386. if (materialMapper.IsCompatible(null))
  387. {
  388. materialMappers.Add(materialMapper);
  389. }
  390. else
  391. {
  392. #if UNITY_EDITOR
  393. var assetPath = AssetDatabase.GetAssetPath(materialMapper);
  394. if (assetPath == null)
  395. {
  396. Object.DestroyImmediate(materialMapper);
  397. }
  398. #else
  399. Object.Destroy(materialMapper);
  400. #endif
  401. }
  402. }
  403. }
  404. if (materialMappers.Count == 0)
  405. {
  406. Debug.LogWarning("TriLib could not find any suitable MaterialMapper on the project.");
  407. }
  408. else
  409. {
  410. assetLoaderOptions.MaterialMappers = materialMappers.ToArray();
  411. }
  412. return assetLoaderOptions;
  413. }
  414. /// <summary>
  415. /// Tries to create a ScriptableObject with the given parameters, without throwing an internal Exception.
  416. /// </summary>
  417. /// <param name="typeName">The ScriptableObject type name.</param>
  418. /// <param name="namespace">The ScriptableObject type namespace.</param>
  419. /// <returns>The created ScriptableObject, or <c>null</c>.</returns>
  420. private static ScriptableObject CreateScriptableObjectSafe(string typeName, string @namespace)
  421. {
  422. var type = System.Type.GetType($"{@namespace}.{typeName}");
  423. return type != null ? ScriptableObject.CreateInstance(typeName) : null;
  424. }
  425. /// <summary>Processes the Model from the given context and begin to build the Game Objects.</summary>
  426. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  427. private static void ProcessModel(AssetLoaderContext assetLoaderContext)
  428. {
  429. if (assetLoaderContext.RootModel != null)
  430. {
  431. CreateModel(assetLoaderContext, assetLoaderContext.WrapperGameObject != null ? assetLoaderContext.WrapperGameObject.transform : null, assetLoaderContext.RootModel, assetLoaderContext.RootModel, true);
  432. if (assetLoaderContext.RootGameObject.transform.localScale.sqrMagnitude == 0f)
  433. {
  434. assetLoaderContext.RootGameObject.transform.localScale = Vector3.one;
  435. }
  436. SetupModelLod(assetLoaderContext, assetLoaderContext.RootModel);
  437. if (assetLoaderContext.Options.AnimationType != AnimationType.None || assetLoaderContext.Options.ImportBlendShapes)
  438. {
  439. SetupModelBones(assetLoaderContext, assetLoaderContext.RootModel);
  440. BuildGameObjectsPaths(assetLoaderContext);
  441. SetupRig(assetLoaderContext);
  442. }
  443. assetLoaderContext.RootGameObject.isStatic = assetLoaderContext.Options.Static;
  444. }
  445. assetLoaderContext.OnLoad?.Invoke(assetLoaderContext);
  446. }
  447. /// <summary>Configures the context Model LODs (levels-of-detail) if there are any.</summary>
  448. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  449. /// <param name="model">The Model containing the LOD data.</param>
  450. private static void SetupModelLod(AssetLoaderContext assetLoaderContext, IModel model)
  451. {
  452. if (model.Children != null && model.Children.Count > 0)
  453. {
  454. var lodModels = new Dictionary<int, List<Renderer>>(model.Children.Count);
  455. var minLod = int.MaxValue;
  456. var maxLod = 0;
  457. for (var i = 0; i < model.Children.Count; i++)
  458. {
  459. var child = model.Children[i];
  460. var match = Regex.Match(child.Name, "_LOD(?<number>[0-9]+)|LOD_(?<number>[0-9]+)");
  461. if (match.Success)
  462. {
  463. var lodNumber = Convert.ToInt32(match.Groups["number"].Value);
  464. minLod = Mathf.Min(lodNumber, minLod);
  465. maxLod = Mathf.Max(lodNumber, maxLod);
  466. if (!lodModels.TryGetValue(lodNumber, out var renderers))
  467. {
  468. renderers = new List<Renderer>();
  469. lodModels.Add(lodNumber, renderers);
  470. }
  471. renderers.AddRange(assetLoaderContext.GameObjects[child].GetComponentsInChildren<Renderer>());
  472. }
  473. }
  474. if (lodModels.Count > 1)
  475. {
  476. var newGameObject = assetLoaderContext.GameObjects[model];
  477. var lods = new List<LOD>(lodModels.Count + 1);
  478. var lodGroup = newGameObject.AddComponent<LODGroup>();
  479. var lastPosition = assetLoaderContext.Options.LODScreenRelativeTransitionHeightBase;
  480. for (var i = minLod; i <= maxLod; i++)
  481. {
  482. if (lodModels.TryGetValue(i, out var renderers))
  483. {
  484. lods.Add(new LOD(lastPosition, renderers.ToArray()));
  485. lastPosition *= 0.5f;
  486. }
  487. }
  488. lodGroup.SetLODs(lods.ToArray());
  489. }
  490. for (var i = 0; i < model.Children.Count; i++)
  491. {
  492. var child = model.Children[i];
  493. SetupModelLod(assetLoaderContext, child);
  494. }
  495. }
  496. }
  497. /// <summary>Builds the Game Object Converts hierarchy paths.</summary>
  498. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  499. private static void BuildGameObjectsPaths(AssetLoaderContext assetLoaderContext)
  500. {
  501. foreach (var value in assetLoaderContext.GameObjects.Values)
  502. {
  503. assetLoaderContext.GameObjectPaths.Add(value, value.transform.BuildPath(assetLoaderContext.RootGameObject.transform));
  504. }
  505. }
  506. /// <summary>Configures the context Model rigging if there is any.</summary>
  507. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  508. private static void SetupRig(AssetLoaderContext assetLoaderContext)
  509. {
  510. var animations = assetLoaderContext.RootModel.AllAnimations;
  511. AnimationClip[] animationClips = null;
  512. if (assetLoaderContext.Options.AnimationType == AnimationType.Humanoid || animations != null && animations.Count > 0)
  513. {
  514. switch (assetLoaderContext.Options.AnimationType)
  515. {
  516. case AnimationType.Legacy:
  517. {
  518. SetupAnimationComponents(assetLoaderContext, animations, out animationClips, out var animator, out var unityAnimation);
  519. break;
  520. }
  521. case AnimationType.Generic:
  522. {
  523. SetupAnimationComponents(assetLoaderContext, animations, out animationClips, out var animator, out var unityAnimation);
  524. if (assetLoaderContext.Options.AvatarDefinition == AvatarDefinitionType.CopyFromOtherAvatar)
  525. {
  526. animator.avatar = assetLoaderContext.Options.Avatar;
  527. }
  528. else
  529. {
  530. SetupGenericAvatar(assetLoaderContext, animator);
  531. }
  532. break;
  533. }
  534. case AnimationType.Humanoid:
  535. {
  536. SetupAnimationComponents(assetLoaderContext, animations, out animationClips, out var animator, out var unityAnimation);
  537. if (assetLoaderContext.Options.AvatarDefinition == AvatarDefinitionType.CopyFromOtherAvatar)
  538. {
  539. animator.avatar = assetLoaderContext.Options.Avatar;
  540. }
  541. else if (assetLoaderContext.Options.HumanoidAvatarMapper != null)
  542. {
  543. SetupHumanoidAvatar(assetLoaderContext, animator);
  544. }
  545. break;
  546. }
  547. }
  548. if (animationClips != null)
  549. {
  550. if (assetLoaderContext.Options.AnimationClipMappers != null)
  551. {
  552. Array.Sort(assetLoaderContext.Options.AnimationClipMappers, (a, b) => a.CheckingOrder > b.CheckingOrder ? -1 : 1);
  553. foreach (var animationClipMapper in assetLoaderContext.Options.AnimationClipMappers)
  554. {
  555. animationClips = animationClipMapper.MapArray(assetLoaderContext, animationClips);
  556. if (animationClips != null && animationClips.Length > 0)
  557. {
  558. break;
  559. }
  560. }
  561. }
  562. for (var i = 0; i < animationClips.Length; i++)
  563. {
  564. var animationClip = animationClips[i];
  565. assetLoaderContext.Allocations.Add(animationClip);
  566. }
  567. }
  568. }
  569. }
  570. /// <summary>
  571. /// Creates animation components for the given context.
  572. /// </summary>
  573. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  574. /// <param name="animations">The Animations loaded for the Model.</param>
  575. /// <param name="animationClips">The AnimationClips that will be created for the Model.</param>
  576. /// <param name="animator">The Animator that will be created for the Model.</param>
  577. /// <param name="unityAnimation">The Animation Component that will be created for the Model.</param>
  578. private static void SetupAnimationComponents(AssetLoaderContext assetLoaderContext, IList<IAnimation> animations, out AnimationClip[] animationClips, out Animator animator, out Animation unityAnimation)
  579. {
  580. if (assetLoaderContext.Options.AnimationType == AnimationType.Legacy && assetLoaderContext.Options.EnforceAnimatorWithLegacyAnimations || assetLoaderContext.Options.AnimationType != AnimationType.Legacy)
  581. {
  582. animator = assetLoaderContext.RootGameObject.AddComponent<Animator>();
  583. }
  584. else
  585. {
  586. animator = null;
  587. }
  588. unityAnimation = assetLoaderContext.RootGameObject.AddComponent<Animation>();
  589. unityAnimation.playAutomatically = assetLoaderContext.Options.AutomaticallyPlayLegacyAnimations;
  590. unityAnimation.wrapMode = assetLoaderContext.Options.AnimationWrapMode;
  591. if (animations != null)
  592. {
  593. animationClips = new AnimationClip[animations.Count];
  594. for (var i = 0; i < animations.Count; i++)
  595. {
  596. var triLibAnimation = animations[i];
  597. var animationClip = CreateAnimation(assetLoaderContext, triLibAnimation);
  598. unityAnimation.AddClip(animationClip, animationClip.name);
  599. animationClips[i] = animationClip;
  600. assetLoaderContext.Reader.UpdateLoadingPercentage(i, assetLoaderContext.Reader.LoadingStepsCount + (int)ReaderBase.PostLoadingSteps.PostProcessAnimationClips, animations.Count);
  601. }
  602. if (assetLoaderContext.Options.AutomaticallyPlayLegacyAnimations && animationClips.Length > 0)
  603. {
  604. unityAnimation.clip = animationClips[0];
  605. unityAnimation.Play(animationClips[0].name);
  606. }
  607. }
  608. else
  609. {
  610. animationClips = null;
  611. }
  612. }
  613. /// <summary>Creates a Skeleton Bone for the given Transform.</summary>
  614. /// <param name="boneTransform">The bone Transform to use on the Skeleton Bone.</param>
  615. /// <returns>The created Skeleton Bone.</returns>
  616. private static SkeletonBone CreateSkeletonBone(Transform boneTransform)
  617. {
  618. var skeletonBone = new SkeletonBone
  619. {
  620. name = boneTransform.name,
  621. position = boneTransform.localPosition,
  622. rotation = boneTransform.localRotation,
  623. scale = boneTransform.localScale
  624. };
  625. return skeletonBone;
  626. }
  627. /// <summary>Creates a Human Bone for the given Bone Mapping, containing the relationship between the Transform and Bone.</summary>
  628. /// <param name="boneMapping">The Bone Mapping used to create the Human Bone, containing the information used to search for bones.</param>
  629. /// <param name="boneName">The bone name to use on the created Human Bone.</param>
  630. /// <returns>The created Human Bone.</returns>
  631. private static HumanBone CreateHumanBone(BoneMapping boneMapping, string boneName)
  632. {
  633. var humanBone = new HumanBone
  634. {
  635. boneName = boneName,
  636. humanName = GetHumanBodyName(boneMapping.HumanBone),
  637. limit =
  638. {
  639. useDefaultValues = boneMapping.HumanLimit.useDefaultValues,
  640. axisLength = boneMapping.HumanLimit.axisLength,
  641. center = boneMapping.HumanLimit.center,
  642. max = boneMapping.HumanLimit.max,
  643. min = boneMapping.HumanLimit.min
  644. }
  645. };
  646. return humanBone;
  647. }
  648. /// <summary>Returns the given Human Body Bones name as String.</summary>
  649. /// <param name="humanBodyBones">The Human Body Bones to get the name from.</param>
  650. /// <returns>The Human Body Bones name.</returns>
  651. private static string GetHumanBodyName(HumanBodyBones humanBodyBones)
  652. {
  653. return HumanTrait.BoneName[(int)humanBodyBones];
  654. }
  655. /// <summary>Creates a Generic Avatar to the given context Model.</summary>
  656. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  657. /// <param name="animator">The Animator assigned to the given Context Root Game Object.</param>
  658. private static void SetupGenericAvatar(AssetLoaderContext assetLoaderContext, Animator animator)
  659. {
  660. var parent = assetLoaderContext.RootGameObject.transform.parent;
  661. assetLoaderContext.RootGameObject.transform.SetParent(null, true);
  662. var bones = new List<Transform>();
  663. assetLoaderContext.RootModel.GetBones(assetLoaderContext, bones);
  664. var rootBone = assetLoaderContext.Options.RootBoneMapper.Map(assetLoaderContext, bones);
  665. var avatar = AvatarBuilder.BuildGenericAvatar(assetLoaderContext.RootGameObject, rootBone != null ? rootBone.name : "");
  666. avatar.name = $"{assetLoaderContext.RootGameObject.name}Avatar";
  667. animator.avatar = avatar;
  668. assetLoaderContext.RootGameObject.transform.SetParent(parent, true);
  669. }
  670. /// <summary>Creates a Humanoid Avatar to the given context Model.</summary>
  671. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  672. /// <param name="animator">The Animator assigned to the given Context Root Game Object.</param>
  673. private static void SetupHumanoidAvatar(AssetLoaderContext assetLoaderContext, Animator animator)
  674. {
  675. var valid = false;
  676. var mapping = assetLoaderContext.Options.HumanoidAvatarMapper.Map(assetLoaderContext);
  677. if (mapping.Count > 0)
  678. {
  679. var parent = assetLoaderContext.RootGameObject.transform.parent;
  680. var rootGameObjectPosition = assetLoaderContext.RootGameObject.transform.position;
  681. assetLoaderContext.RootGameObject.transform.SetParent(null, false);
  682. assetLoaderContext.Options.HumanoidAvatarMapper.PostSetup(assetLoaderContext, mapping);
  683. Transform hipsTransform = null;
  684. var humanBones = new HumanBone[mapping.Count];
  685. var boneIndex = 0;
  686. foreach (var kvp in mapping)
  687. {
  688. if (kvp.Key.HumanBone == HumanBodyBones.Hips)
  689. {
  690. hipsTransform = kvp.Value;
  691. }
  692. humanBones[boneIndex++] = CreateHumanBone(kvp.Key, kvp.Value.name);
  693. }
  694. if (hipsTransform != null)
  695. {
  696. var skeletonBones = new Dictionary<Transform, SkeletonBone>();
  697. var bounds = assetLoaderContext.RootGameObject.CalculateBounds();
  698. var toBottom = bounds.min.y;
  699. if (toBottom < 0f)
  700. {
  701. var hipsTransformPosition = hipsTransform.position;
  702. hipsTransformPosition.y -= toBottom;
  703. hipsTransform.position = hipsTransformPosition;
  704. }
  705. var toCenter = Vector3.zero - bounds.center;
  706. toCenter.y = 0f;
  707. if (toCenter.sqrMagnitude > 0.01f)
  708. {
  709. var hipsTransformPosition = hipsTransform.position;
  710. hipsTransformPosition += toCenter;
  711. hipsTransform.position = hipsTransformPosition;
  712. }
  713. foreach (var kvp in assetLoaderContext.GameObjects)
  714. {
  715. if (!skeletonBones.ContainsKey(kvp.Value.transform))
  716. {
  717. skeletonBones.Add(kvp.Value.transform, CreateSkeletonBone(kvp.Value.transform));
  718. }
  719. }
  720. var triLibHumanDescription = assetLoaderContext.Options.HumanDescription ?? new General.HumanDescription();
  721. var humanDescription = new HumanDescription
  722. {
  723. armStretch = triLibHumanDescription.armStretch,
  724. feetSpacing = triLibHumanDescription.feetSpacing,
  725. hasTranslationDoF = triLibHumanDescription.hasTranslationDof,
  726. legStretch = triLibHumanDescription.legStretch,
  727. lowerArmTwist = triLibHumanDescription.lowerArmTwist,
  728. lowerLegTwist = triLibHumanDescription.lowerLegTwist,
  729. upperArmTwist = triLibHumanDescription.upperArmTwist,
  730. upperLegTwist = triLibHumanDescription.upperLegTwist,
  731. skeleton = skeletonBones.Values.ToArray(),
  732. human = humanBones
  733. };
  734. var avatar = AvatarBuilder.BuildHumanAvatar(assetLoaderContext.RootGameObject, humanDescription);
  735. avatar.name = $"{assetLoaderContext.RootGameObject.name}Avatar";
  736. animator.avatar = avatar;
  737. }
  738. assetLoaderContext.RootGameObject.transform.SetParent(parent, false);
  739. assetLoaderContext.RootGameObject.transform.position = rootGameObjectPosition;
  740. valid = animator.avatar.isValid || !assetLoaderContext.Options.ShowLoadingWarnings;
  741. }
  742. if (!valid)
  743. {
  744. Debug.LogWarning($"Could not create an Avatar for the model \"{(assetLoaderContext.Filename == null ? "Unknown" : FileUtils.GetShortFilename(assetLoaderContext.Filename))}\"");
  745. }
  746. }
  747. /// <summary>Converts the given Model into a Game Object.</summary>
  748. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  749. /// <param name="parentTransform">The parent Game Object Transform.</param>
  750. /// <param name="rootModel">The root Model.</param>
  751. /// <param name="model">The Model to convert.</param>
  752. /// <param name="isRootGameObject">Is this the first node in the Model hierarchy?</param>
  753. private static void CreateModel(AssetLoaderContext assetLoaderContext, Transform parentTransform, IRootModel rootModel, IModel model, bool isRootGameObject)
  754. {
  755. var newGameObject = new GameObject(model.Name);
  756. assetLoaderContext.GameObjects.Add(model, newGameObject);
  757. assetLoaderContext.Models.Add(newGameObject, model);
  758. newGameObject.transform.parent = parentTransform;
  759. newGameObject.transform.localPosition = model.LocalPosition;
  760. newGameObject.transform.localRotation = model.LocalRotation;
  761. newGameObject.transform.localScale = model.LocalScale;
  762. if (model.GeometryGroup != null)
  763. {
  764. CreateGeometry(assetLoaderContext, newGameObject, rootModel, model);
  765. }
  766. if (assetLoaderContext.Options.ImportCameras && model is ICamera camera)
  767. {
  768. CreateCamera(assetLoaderContext, camera, newGameObject);
  769. }
  770. if (assetLoaderContext.Options.ImportLights && model is ILight light)
  771. {
  772. CreateLight(assetLoaderContext, light, newGameObject);
  773. }
  774. if (model.Children != null && model.Children.Count > 0)
  775. {
  776. for (var i = 0; i < model.Children.Count; i++)
  777. {
  778. var child = model.Children[i];
  779. CreateModel(assetLoaderContext, newGameObject.transform, rootModel, child, false);
  780. }
  781. }
  782. if (assetLoaderContext.Options.UserPropertiesMapper != null && model.UserProperties != null)
  783. {
  784. foreach (var userProperty in model.UserProperties)
  785. {
  786. assetLoaderContext.Options.UserPropertiesMapper.OnProcessUserData(assetLoaderContext, newGameObject, userProperty.Key, userProperty.Value);
  787. }
  788. }
  789. if (isRootGameObject)
  790. {
  791. assetLoaderContext.RootGameObject = newGameObject;
  792. }
  793. }
  794. /// <summary>Converts the given model light, if present into a Light.</summary>
  795. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  796. /// <param name="light">The Model.</param>
  797. /// <param name="newGameObject">The Model Game Object.</param>
  798. private static void CreateLight(AssetLoaderContext assetLoaderContext, ILight light, GameObject newGameObject)
  799. {
  800. var unityLight = newGameObject.AddComponent<Light>();
  801. unityLight.color = light.Color;
  802. unityLight.innerSpotAngle = light.InnerSpotAngle;
  803. unityLight.spotAngle = light.OuterSpotAngle;
  804. unityLight.intensity = light.Intensity;
  805. unityLight.range = light.Range;
  806. unityLight.type = light.LightType;
  807. unityLight.shadows = light.CastShadows ? LightShadows.Soft : LightShadows.None;
  808. #if UNITY_EDITOR
  809. unityLight.areaSize = new Vector2(light.Width, light.Height);
  810. #endif
  811. }
  812. /// <summary>Converts the given model camera, if present into a Camera.</summary>
  813. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  814. /// <param name="camera">The Model.</param>
  815. /// <param name="newGameObject">The Model Game Object.</param>
  816. private static void CreateCamera(AssetLoaderContext assetLoaderContext, ICamera camera, GameObject newGameObject)
  817. {
  818. var unityCamera = newGameObject.AddComponent<Camera>();
  819. unityCamera.aspect = camera.AspectRatio;
  820. unityCamera.orthographic = camera.Ortographic;
  821. unityCamera.orthographicSize = camera.OrtographicSize;
  822. unityCamera.fieldOfView = camera.FieldOfView;
  823. unityCamera.nearClipPlane = camera.NearClipPlane;
  824. unityCamera.farClipPlane = camera.FarClipPlane;
  825. unityCamera.focalLength = camera.FocalLength;
  826. unityCamera.sensorSize = camera.SensorSize;
  827. unityCamera.lensShift = camera.LensShift;
  828. unityCamera.gateFit = camera.GateFitMode;
  829. unityCamera.usePhysicalProperties = camera.PhysicalCamera;
  830. unityCamera.enabled = true;
  831. }
  832. /// <summary>Configures the given Model skinning if there is any.</summary>
  833. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  834. /// <param name="model">The Model containing the bones.</param>
  835. private static void SetupModelBones(AssetLoaderContext assetLoaderContext, IModel model)
  836. {
  837. var loadedGameObject = assetLoaderContext.GameObjects[model];
  838. var skinnedMeshRenderer = loadedGameObject.GetComponent<SkinnedMeshRenderer>();
  839. if (skinnedMeshRenderer != null)
  840. {
  841. var bones = model.Bones;
  842. if (bones != null && bones.Count > 0)
  843. {
  844. var boneIndex = 0;
  845. var gameObjectBones = skinnedMeshRenderer.bones;
  846. for (var i = 0; i < bones.Count; i++)
  847. {
  848. var bone = bones[i];
  849. gameObjectBones[boneIndex++] = assetLoaderContext.GameObjects[bone].transform;
  850. }
  851. skinnedMeshRenderer.bones = gameObjectBones;
  852. skinnedMeshRenderer.rootBone = assetLoaderContext.Options.RootBoneMapper.Map(assetLoaderContext, gameObjectBones);
  853. }
  854. }
  855. if (model.Children != null && model.Children.Count > 0)
  856. {
  857. for (var i = 0; i < model.Children.Count; i++)
  858. {
  859. var subModel = model.Children[i];
  860. SetupModelBones(assetLoaderContext, subModel);
  861. }
  862. }
  863. }
  864. /// <summary>Converts the given Animation into an Animation Clip.</summary>
  865. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  866. /// <param name="animation">The Animation to convert.</param>
  867. /// <returns>The converted Animation Clip.</returns>
  868. private static AnimationClip CreateAnimation(AssetLoaderContext assetLoaderContext, IAnimation animation)
  869. {
  870. var animationClip = new AnimationClip { name = animation.Name, legacy = true, frameRate = animation.FrameRate };
  871. var animationCurveBindings = animation.AnimationCurveBindings;
  872. if (animationCurveBindings == null)
  873. {
  874. return animationClip;
  875. }
  876. for (var i = animationCurveBindings.Count - 1; i >= 0; i--)
  877. {
  878. var animationCurveBinding = animationCurveBindings[i];
  879. var animationCurves = animationCurveBinding.AnimationCurves;
  880. if (!assetLoaderContext.GameObjects.ContainsKey(animationCurveBinding.Model))
  881. {
  882. continue;
  883. }
  884. var gameObject = assetLoaderContext.GameObjects[animationCurveBinding.Model];
  885. for (var j = 0; j < animationCurves.Count; j++)
  886. {
  887. var animationCurve = animationCurves[j];
  888. var unityAnimationCurve = animationCurve.AnimationCurve;
  889. var gameObjectPath = assetLoaderContext.GameObjectPaths[gameObject];
  890. var propertyName = animationCurve.Property;
  891. var propertyType = animationCurve.AnimatedType;
  892. // todo: working on it for a future release
  893. // the simplification isn't working with rotation curves yet
  894. //if (assetLoaderContext.Options.SimplifyAnimations)
  895. //{
  896. // switch (propertyName)
  897. // {
  898. // case Constants.LocalRotationXProperty:
  899. // case Constants.LocalRotationYProperty:
  900. // case Constants.LocalRotationZProperty:
  901. // case Constants.LocalRotationWProperty:
  902. // unityAnimationCurve.Simplify(assetLoaderContext.Options.RotationThreshold, true);
  903. // break;
  904. // case Constants.LocalScaleXProperty:
  905. // case Constants.LocalScaleYProperty:
  906. // case Constants.LocalScaleZProperty:
  907. // unityAnimationCurve.Simplify(assetLoaderContext.Options.ScaleThreshold, true);
  908. // break;
  909. // default:
  910. // unityAnimationCurve.Simplify(assetLoaderContext.Options.PositionThreshold, true);
  911. // break;
  912. // }
  913. //}
  914. animationClip.SetCurve(gameObjectPath, propertyType, propertyName, unityAnimationCurve);
  915. }
  916. }
  917. //Fixed in Unity 2022.1.X
  918. if (assetLoaderContext.Options.EnsureQuaternionContinuity)
  919. {
  920. animationClip.EnsureQuaternionContinuity();
  921. }
  922. return animationClip;
  923. }
  924. /// <summary>Converts the given Geometry Group into a Mesh.</summary>
  925. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  926. /// <param name="meshGameObject">The Game Object where the Mesh belongs.</param>
  927. /// <param name="rootModel">The root Model.</param>
  928. /// <param name="meshModel">The Model used to generate the Game Object.</param>
  929. private static void CreateGeometry(AssetLoaderContext assetLoaderContext, GameObject meshGameObject, IRootModel rootModel, IModel meshModel)
  930. {
  931. var geometryGroup = meshModel.GeometryGroup;
  932. if (geometryGroup.GeometriesData != null)
  933. {
  934. if (geometryGroup.Mesh == null)
  935. {
  936. geometryGroup.GenerateMesh(assetLoaderContext, assetLoaderContext.Options.AnimationType == AnimationType.None ? null : meshModel.BindPoses, meshModel.MaterialIndices);
  937. }
  938. assetLoaderContext.Allocations.Add(geometryGroup.Mesh);
  939. if (assetLoaderContext.Options.MarkMeshesAsDynamic)
  940. {
  941. geometryGroup.Mesh.MarkDynamic();
  942. }
  943. if (assetLoaderContext.Options.LipSyncMappers != null)
  944. {
  945. Array.Sort(assetLoaderContext.Options.LipSyncMappers, (a, b) => a.CheckingOrder > b.CheckingOrder ? -1 : 1);
  946. foreach (var lipSyncMapper in assetLoaderContext.Options.LipSyncMappers)
  947. {
  948. if (lipSyncMapper.Map(assetLoaderContext, geometryGroup, out var visemeToBlendTargets))
  949. {
  950. var lipSyncMapping = meshGameObject.AddComponent<LipSyncMapping>();
  951. lipSyncMapping.VisemeToBlendTargets = visemeToBlendTargets;
  952. break;
  953. }
  954. }
  955. }
  956. if (assetLoaderContext.Options.GenerateColliders)
  957. {
  958. if (assetLoaderContext.RootModel.AllAnimations != null && assetLoaderContext.RootModel.AllAnimations.Count > 0 && assetLoaderContext.Options.ShowLoadingWarnings)
  959. {
  960. Debug.LogWarning("Adding a MeshCollider to an animated object.");
  961. }
  962. var meshCollider = meshGameObject.AddComponent<MeshCollider>();
  963. meshCollider.sharedMesh = geometryGroup.Mesh;
  964. meshCollider.convex = assetLoaderContext.Options.ConvexColliders;
  965. }
  966. Renderer renderer = null;
  967. if (assetLoaderContext.Options.AnimationType != AnimationType.None || assetLoaderContext.Options.ImportBlendShapes)
  968. {
  969. var bones = assetLoaderContext.Options.AddAllBonesToSkinnedMeshRenderers ? GetAllBonesRecursive(assetLoaderContext) : meshModel.Bones;
  970. var geometryGroupBlendShapeGeometryBindings = geometryGroup.BlendShapeKeys;
  971. if ((bones != null && bones.Count > 0 || geometryGroupBlendShapeGeometryBindings != null && geometryGroupBlendShapeGeometryBindings.Count > 0) && assetLoaderContext.Options.AnimationType != AnimationType.None)
  972. {
  973. var skinnedMeshRenderer = meshGameObject.AddComponent<SkinnedMeshRenderer>();
  974. skinnedMeshRenderer.sharedMesh = geometryGroup.Mesh;
  975. skinnedMeshRenderer.enabled = !assetLoaderContext.Options.ImportVisibility || meshModel.Visibility;
  976. if (bones != null && bones.Count > 0)
  977. {
  978. skinnedMeshRenderer.bones = new Transform[bones.Count];
  979. }
  980. renderer = skinnedMeshRenderer;
  981. }
  982. }
  983. if (renderer == null)
  984. {
  985. var meshFilter = meshGameObject.AddComponent<MeshFilter>();
  986. meshFilter.sharedMesh = geometryGroup.Mesh;
  987. if (!assetLoaderContext.Options.LoadPointClouds)
  988. {
  989. var meshRenderer = meshGameObject.AddComponent<MeshRenderer>();
  990. meshRenderer.enabled = !assetLoaderContext.Options.ImportVisibility || meshModel.Visibility;
  991. renderer = meshRenderer;
  992. }
  993. }
  994. if (renderer != null)
  995. {
  996. Material loadingMaterial = null;
  997. if (assetLoaderContext.Options.MaterialMappers != null)
  998. {
  999. for (var i = 0; i < assetLoaderContext.Options.MaterialMappers.Length; i++)
  1000. {
  1001. var mapper = assetLoaderContext.Options.MaterialMappers[i];
  1002. if (mapper != null && mapper.IsCompatible(null))
  1003. {
  1004. loadingMaterial = mapper.LoadingMaterial;
  1005. break;
  1006. }
  1007. }
  1008. }
  1009. var unityMaterials = new Material[geometryGroup.GeometriesData.Count];
  1010. if (loadingMaterial == null)
  1011. {
  1012. if (assetLoaderContext.Options.ShowLoadingWarnings)
  1013. {
  1014. Debug.LogWarning("Could not find a suitable loading Material.");
  1015. }
  1016. }
  1017. else
  1018. {
  1019. for (var i = 0; i < unityMaterials.Length; i++)
  1020. {
  1021. unityMaterials[i] = loadingMaterial;
  1022. }
  1023. }
  1024. renderer.sharedMaterials = unityMaterials;
  1025. var materialIndices = meshModel.MaterialIndices;
  1026. foreach (var geometryData in geometryGroup.GeometriesData)
  1027. {
  1028. var geometry = geometryData.Value;
  1029. if (geometry == null)
  1030. {
  1031. continue;
  1032. }
  1033. var originalGeometryIndex = geometry.OriginalIndex;
  1034. var materialIndex = materialIndices[originalGeometryIndex];
  1035. if (materialIndex < 0 || materialIndex >= rootModel.AllMaterials.Count)
  1036. {
  1037. continue;
  1038. }
  1039. var sourceMaterial = rootModel.AllMaterials[materialIndex];
  1040. if (sourceMaterial == null)
  1041. {
  1042. continue;
  1043. }
  1044. if (originalGeometryIndex < 0 || originalGeometryIndex >= renderer.sharedMaterials.Length)
  1045. {
  1046. continue;
  1047. }
  1048. var materialRenderersContext = new MaterialRendererContext
  1049. {
  1050. Context = assetLoaderContext,
  1051. Renderer = renderer,
  1052. GeometryIndex = geometry.Index,
  1053. Material = sourceMaterial
  1054. };
  1055. if (assetLoaderContext.MaterialRenderers.TryGetValue(sourceMaterial, out var materialRendererContextList))
  1056. {
  1057. materialRendererContextList.Add(materialRenderersContext);
  1058. }
  1059. else
  1060. {
  1061. assetLoaderContext.MaterialRenderers.Add(sourceMaterial, new List<MaterialRendererContext> { materialRenderersContext });
  1062. }
  1063. }
  1064. }
  1065. }
  1066. }
  1067. /// <summary>
  1068. /// Creates a list with every bone in the loaded model.
  1069. /// </summary>
  1070. private static IList<IModel> GetAllBonesRecursive(AssetLoaderContext assetLoaderContext)
  1071. {
  1072. var bones = new List<IModel>();
  1073. foreach (var model in assetLoaderContext.RootModel.AllModels)
  1074. {
  1075. if (model.IsBone)
  1076. {
  1077. bones.Add(model);
  1078. }
  1079. }
  1080. return bones;
  1081. }
  1082. /// <summary>Loads the root Model.</summary>
  1083. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  1084. private static void LoadModel(AssetLoaderContext assetLoaderContext)
  1085. {
  1086. SetupModelLoading(assetLoaderContext);
  1087. }
  1088. private static void SetupModelLoading(AssetLoaderContext assetLoaderContext)
  1089. {
  1090. if (assetLoaderContext.Stream == null && string.IsNullOrWhiteSpace(assetLoaderContext.Filename))
  1091. {
  1092. throw new Exception("TriLib is unable to load the given file.");
  1093. }
  1094. if (assetLoaderContext.Options.MaterialMappers != null)
  1095. {
  1096. Array.Sort(assetLoaderContext.Options.MaterialMappers, (a, b) => a.CheckingOrder > b.CheckingOrder ? -1 : 1);
  1097. }
  1098. else
  1099. {
  1100. if (assetLoaderContext.Options.ShowLoadingWarnings)
  1101. {
  1102. Debug.LogWarning("Your AssetLoaderOptions instance has no MaterialMappers. TriLib can't process materials without them.");
  1103. }
  1104. }
  1105. #if TRILIB_DRACO
  1106. GltfReader.DracoDecompressorCallback = DracoMeshLoader.DracoDecompressorCallback;
  1107. #endif
  1108. var fileExtension = assetLoaderContext.FileExtension;
  1109. if (fileExtension == null)
  1110. {
  1111. fileExtension = FileUtils.GetFileExtension(assetLoaderContext.Filename, false);
  1112. }
  1113. else if (fileExtension[0] == '.' && fileExtension.Length > 1)
  1114. {
  1115. fileExtension = fileExtension.Substring(1);
  1116. }
  1117. if (assetLoaderContext.Stream == null)
  1118. {
  1119. var fileStream = new FileStream(assetLoaderContext.Filename, FileMode.Open, FileAccess.Read, FileShare.Read);
  1120. assetLoaderContext.Stream = fileStream;
  1121. var reader = Readers.FindReaderForExtension(fileExtension);
  1122. if (reader != null)
  1123. {
  1124. assetLoaderContext.RootModel = reader.ReadStream(fileStream, assetLoaderContext, assetLoaderContext.Filename, assetLoaderContext.OnProgress);
  1125. }
  1126. }
  1127. else
  1128. {
  1129. var reader = Readers.FindReaderForExtension(fileExtension);
  1130. if (reader != null)
  1131. {
  1132. assetLoaderContext.RootModel = reader.ReadStream(assetLoaderContext.Stream, assetLoaderContext, assetLoaderContext.Filename, assetLoaderContext.OnProgress);
  1133. }
  1134. else
  1135. {
  1136. throw new Exception("Could not find a suitable reader for the given model. Please fill the 'fileExtension' parameter when calling any model loading method.");
  1137. }
  1138. if (assetLoaderContext.RootModel == null)
  1139. {
  1140. throw new Exception("TriLib could not load the given model.");
  1141. }
  1142. }
  1143. }
  1144. /// <summary>Processes the root Model.</summary>
  1145. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  1146. private static void ProcessRootModel(AssetLoaderContext assetLoaderContext)
  1147. {
  1148. ProcessModel(assetLoaderContext);
  1149. ProcessMaterials(assetLoaderContext);
  1150. }
  1151. /// <summary>
  1152. /// Processes the Model Materials, if all source Materials have been loaded.
  1153. /// </summary>
  1154. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  1155. private static void ProcessMaterials(AssetLoaderContext assetLoaderContext)
  1156. {
  1157. if (assetLoaderContext.RootModel?.AllMaterials != null && assetLoaderContext.RootModel.AllMaterials.Count > 0)
  1158. {
  1159. if (assetLoaderContext.Options.MaterialMappers != null)
  1160. {
  1161. ProcessMaterialRenderers(assetLoaderContext);
  1162. }
  1163. else if (assetLoaderContext.Options.ShowLoadingWarnings)
  1164. {
  1165. Debug.LogWarning("Please specify a TriLib Material Mapper, otherwise Materials can't be created.");
  1166. }
  1167. }
  1168. else
  1169. {
  1170. if (assetLoaderContext.Options.DiscardUnusedTextures)
  1171. {
  1172. FinishLoading(assetLoaderContext);
  1173. }
  1174. else
  1175. {
  1176. LoadUnusedTextures(assetLoaderContext);
  1177. }
  1178. }
  1179. }
  1180. /// <summary>
  1181. /// Loads the unused Textures and adds them to the allocations list.
  1182. /// </summary>
  1183. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  1184. private static void LoadUnusedTextures(AssetLoaderContext assetLoaderContext)
  1185. {
  1186. if (assetLoaderContext.RootGameObject != null)
  1187. {
  1188. if (assetLoaderContext.RootModel.AllTextures != null)
  1189. {
  1190. foreach (var texture in assetLoaderContext.RootModel.AllTextures)
  1191. {
  1192. var textureLoadingContext = new TextureLoadingContext()
  1193. {
  1194. Texture = texture,
  1195. Context = assetLoaderContext
  1196. };
  1197. if (!assetLoaderContext.TryGetLoadedTexture(textureLoadingContext, out _))
  1198. {
  1199. if (assetLoaderContext.Options.UseUnityNativeTextureLoader)
  1200. {
  1201. TextureLoaders.LoadTexture(textureLoadingContext);
  1202. }
  1203. else
  1204. {
  1205. TextureLoaders.CreateTexture(textureLoadingContext);
  1206. TextureLoaders.LoadTexture(textureLoadingContext);
  1207. }
  1208. }
  1209. }
  1210. }
  1211. }
  1212. FinishLoading(assetLoaderContext);
  1213. }
  1214. ///<summary>
  1215. /// Finishes the Model loading, calling the OnMaterialsLoad callback, if present.
  1216. ///</summary>
  1217. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  1218. private static void FinishLoading(AssetLoaderContext assetLoaderContext)
  1219. {
  1220. if (assetLoaderContext.Options.AddAssetUnloader && (assetLoaderContext.RootGameObject != null || assetLoaderContext.WrapperGameObject != null))
  1221. {
  1222. var gameObject = assetLoaderContext.RootGameObject ?? assetLoaderContext.WrapperGameObject;
  1223. var assetUnloader = gameObject.AddComponent<AssetUnloader>();
  1224. assetUnloader.Id = AssetUnloader.GetNextId();
  1225. assetUnloader.Allocations = assetLoaderContext.Allocations;
  1226. assetUnloader.CustomData = assetLoaderContext.CustomData;
  1227. }
  1228. if (assetLoaderContext.Options.DiscardUnusedTextures)
  1229. {
  1230. assetLoaderContext.DiscardUnusedTextures();
  1231. }
  1232. assetLoaderContext.Reader?.UpdateLoadingPercentage(1f, assetLoaderContext.Reader.LoadingStepsCount + (int)ReaderBase.PostLoadingSteps.FinishedProcessing);
  1233. assetLoaderContext.OnMaterialsLoad?.Invoke(assetLoaderContext);
  1234. Cleanup(assetLoaderContext);
  1235. }
  1236. /// <summary>
  1237. /// Processes Model Renderers.
  1238. /// </summary>
  1239. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  1240. private static void ProcessMaterialRenderers(AssetLoaderContext assetLoaderContext)
  1241. {
  1242. var materialMapperContexts = new MaterialMapperContext[assetLoaderContext.RootModel.AllMaterials.Count];
  1243. for (var i = 0; i < assetLoaderContext.RootModel.AllMaterials.Count; i++)
  1244. {
  1245. var material = assetLoaderContext.RootModel.AllMaterials[i];
  1246. var materialMapperContext = new MaterialMapperContext()
  1247. {
  1248. Context = assetLoaderContext,
  1249. Material = material
  1250. };
  1251. materialMapperContexts[i] = materialMapperContext;
  1252. for (var j = 0; j < assetLoaderContext.Options.MaterialMappers.Length; j++)
  1253. {
  1254. var materialMapper = assetLoaderContext.Options.MaterialMappers[j];
  1255. if (materialMapper is object && materialMapper.IsCompatible(materialMapperContext))
  1256. {
  1257. materialMapperContext.MaterialMapper = materialMapper;
  1258. materialMapper.Map(materialMapperContext);
  1259. ApplyMaterialToRenderers(materialMapperContext);
  1260. //materialMapperContext.AddPostProcessingActionToMainThread(ApplyMaterialToRenderers, materialMapperContext);
  1261. break;
  1262. }
  1263. }
  1264. assetLoaderContext.Reader.UpdateLoadingPercentage(i, assetLoaderContext.Reader.LoadingStepsCount + (int)ReaderBase.PostLoadingSteps.PostProcessRenderers, assetLoaderContext.RootModel.AllMaterials.Count);
  1265. }
  1266. if (assetLoaderContext.Options.DiscardUnusedTextures)
  1267. {
  1268. FinishLoading(assetLoaderContext);
  1269. //assetLoaderContext.ExecuteActionsQueue(FinishLoading);
  1270. }
  1271. else
  1272. {
  1273. LoadUnusedTextures(assetLoaderContext);
  1274. //assetLoaderContext.ExecuteActionsQueue(LoadUnusedTextures);
  1275. }
  1276. }
  1277. /// <summary>
  1278. /// Applies the Material from the given context to its Renderers.
  1279. /// </summary>
  1280. /// <param name="materialMapperContext">The source Material Mapper Context, containing the Virtual Material and Unity Material.</param>
  1281. private static void ApplyMaterialToRenderers(MaterialMapperContext materialMapperContext)
  1282. {
  1283. materialMapperContext.Completed = false;
  1284. if (materialMapperContext.Context.MaterialRenderers.TryGetValue(materialMapperContext.Material, out var materialRendererList))
  1285. {
  1286. for (var k = 0; k < materialRendererList.Count; k++)
  1287. {
  1288. var materialRendererContext = materialRendererList[k];
  1289. materialRendererContext.MaterialMapperContext = materialMapperContext;
  1290. materialMapperContext.MaterialMapper.ApplyMaterialToRenderer(materialRendererContext);
  1291. }
  1292. }
  1293. materialMapperContext.Completed = true;
  1294. }
  1295. /// <summary>Handles all Model loading errors, unloads the partially loaded Model (if suitable), and calls the error callback (if existing).</summary>
  1296. /// <param name="error">The Contextualized Error that has occurred.</param>
  1297. private static void HandleError(IContextualizedError error)
  1298. {
  1299. var exception = error.GetInnerException();
  1300. if (error.GetContext() is IAssetLoaderContext context)
  1301. {
  1302. var assetLoaderContext = context.Context;
  1303. if (assetLoaderContext != null)
  1304. {
  1305. Cleanup(assetLoaderContext);
  1306. if (assetLoaderContext.Options.DestroyOnError && assetLoaderContext.RootGameObject != null)
  1307. {
  1308. if (!Application.isPlaying)
  1309. {
  1310. Object.DestroyImmediate(assetLoaderContext.RootGameObject);
  1311. }
  1312. else
  1313. {
  1314. Object.Destroy(assetLoaderContext.RootGameObject);
  1315. }
  1316. assetLoaderContext.RootGameObject = null;
  1317. }
  1318. if (assetLoaderContext.OnError != null)
  1319. {
  1320. Dispatcher.InvokeAsync(assetLoaderContext.OnError, error);
  1321. }
  1322. }
  1323. }
  1324. else
  1325. {
  1326. var contextualizedError = new ContextualizedError<object>(exception, null);
  1327. Dispatcher.InvokeAsync(Rethrow, contextualizedError);
  1328. }
  1329. }
  1330. /// <summary>
  1331. /// Tries to close the Model Stream, if the used AssetLoaderOptions.CloseSteamAutomatically option is enabled.
  1332. /// </summary>
  1333. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  1334. private static void Cleanup(AssetLoaderContext assetLoaderContext)
  1335. {
  1336. if (assetLoaderContext.Stream != null && assetLoaderContext.Options.CloseStreamAutomatically)
  1337. {
  1338. assetLoaderContext.Stream.TryToDispose();
  1339. }
  1340. //Resources.UnloadUnusedAssets();
  1341. GC.Collect();
  1342. GC.WaitForPendingFinalizers();
  1343. GC.Collect();
  1344. }
  1345. /// <summary>Throws the given Contextualized Error on the main Thread.</summary>
  1346. /// <typeparam name="T"></typeparam>
  1347. /// <param name="contextualizedError">The Contextualized Error to throw.</param>
  1348. private static void Rethrow<T>(ContextualizedError<T> contextualizedError)
  1349. {
  1350. throw contextualizedError;
  1351. }
  1352. }
  1353. }