AssetViewer.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  1. #pragma warning disable 649
  2. #pragma warning disable 108
  3. #pragma warning disable 618
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using System.Linq;
  10. using TriLibCore.SFB;
  11. using TriLibCore.Extensions;
  12. using TriLibCore.General;
  13. using TriLibCore.Utils;
  14. using UnityEngine;
  15. using UnityEngine.EventSystems;
  16. using UnityEngine.Rendering;
  17. using UnityEngine.UI;
  18. using UnityEngine.Profiling;
  19. namespace TriLibCore.Samples
  20. {
  21. /// <summary>Represents a TriLib sample which allows the user to load models and HDR skyboxes from the local file-system.</summary>
  22. public class AssetViewer : AssetViewerBase
  23. {
  24. /// <summary>
  25. /// Maximum camera distance ratio based on model bounds.
  26. /// </summary>
  27. private const float MaxCameraDistanceRatio = 3f;
  28. /// <summary>
  29. /// Camera distance ratio based on model bounds.
  30. /// </summary>
  31. protected const float CameraDistanceRatio = 2f;
  32. /// <summary>
  33. /// minimum camera distance.
  34. /// </summary>
  35. protected const float MinCameraDistance = 0.01f;
  36. /// <summary>
  37. /// Skybox scale based on model bounds.
  38. /// </summary>
  39. protected const float SkyboxScale = 100f;
  40. /// <summary>
  41. /// Skybox game object.
  42. /// </summary>
  43. [SerializeField]
  44. protected GameObject Skybox;
  45. /// <summary>
  46. /// Scene CanvasScaler.
  47. /// </summary>
  48. [SerializeField]
  49. protected CanvasScaler CanvasScaler;
  50. /// <summary>
  51. /// Camera selection Dropdown.
  52. /// </summary>
  53. [SerializeField]
  54. private Dropdown _camerasDropdown;
  55. /// <summary>
  56. /// Camera loading Toggle.
  57. /// </summary>
  58. [SerializeField]
  59. private Toggle _loadCamerasToggle;
  60. /// <summary>
  61. /// Lights loading Toggle.
  62. /// </summary>
  63. [SerializeField]
  64. private Toggle _loadLightsToggle;
  65. /// <summary>
  66. /// Point Clouds loading Toggle.
  67. /// </summary>
  68. [SerializeField]
  69. private Toggle _loadPointClouds;
  70. /// <summary>
  71. /// Skybox game object renderer.
  72. /// </summary>
  73. [SerializeField]
  74. private Renderer _skyboxRenderer;
  75. /// <summary>
  76. /// Directional light.
  77. /// </summary>
  78. [SerializeField]
  79. private Light _light;
  80. /// <summary>
  81. /// Skybox material preset to create the final skybox material.
  82. /// </summary>
  83. [SerializeField]
  84. private Material _skyboxMaterialPreset;
  85. /// <summary>
  86. /// Main reflection probe.
  87. /// </summary>
  88. [SerializeField]
  89. private ReflectionProbe _reflectionProbe;
  90. /// <summary>
  91. /// Skybox exposure slider.
  92. /// </summary>
  93. [SerializeField]
  94. private Slider _skyboxExposureSlider;
  95. /// <summary>
  96. /// Loading time indicator.
  97. /// </summary>
  98. [SerializeField]
  99. private Text _loadingTimeText;
  100. /// <summary>
  101. /// Memory usage Text.
  102. /// </summary>
  103. [SerializeField]
  104. private Text _memoryUsageText;
  105. /// <summary>
  106. /// Error panel.
  107. /// </summary>
  108. [SerializeField]
  109. private GameObject _errorPanel;
  110. /// <summary>
  111. /// Error panel inner text.
  112. /// </summary>
  113. [SerializeField]
  114. private Text _errorPanelText;
  115. /// <summary>
  116. /// Main scene Camera.
  117. /// </summary>
  118. [SerializeField]
  119. private Camera _mainCamera;
  120. /// <summary>
  121. /// Debug options dropdown;
  122. /// </summary>
  123. [SerializeField]
  124. private Dropdown _debugOptionsDropdown;
  125. /// <summary>
  126. /// Text used to display the used memory per object type.
  127. /// </summary>
  128. [SerializeField]
  129. private Text _usedMemoryText;
  130. /// <summary>
  131. /// Current camera distance.
  132. /// </summary>
  133. protected float CameraDistance = 1f;
  134. /// <summary>
  135. /// Current camera pivot position.
  136. /// </summary>
  137. protected Vector3 CameraPivot;
  138. /// <summary>
  139. /// Input multiplier based on loaded model bounds.
  140. /// </summary>
  141. protected float InputMultiplier = 1f;
  142. /// <summary>
  143. /// Skybox instantiated material.
  144. /// </summary>
  145. private Material _skyboxMaterial;
  146. /// <summary>
  147. /// Texture loaded for skybox.
  148. /// </summary>
  149. private Texture2D _skyboxTexture;
  150. /// <summary>
  151. /// List of loaded animations.
  152. /// </summary>
  153. private List<AnimationClip> _animations;
  154. /// <summary>
  155. /// Created animation component for the loaded model.
  156. /// </summary>
  157. private Animation _animation;
  158. /// <summary>
  159. /// Loaded model cameras.
  160. /// </summary>
  161. private IList<Camera> _cameras;
  162. /// <summary>
  163. /// Stop Watch used to track the model loading time.
  164. /// </summary>
  165. private Stopwatch _stopwatch;
  166. /// <summary>
  167. /// Current directional light angle.
  168. /// </summary>
  169. private Vector2 _lightAngle = new Vector2(0f, -45f);
  170. /// <summary>
  171. /// Reference to the ShowSkeleton behavior added to the loaded game object.
  172. /// </summary>
  173. private ShowSkeleton _showSkeleton;
  174. /// <summary>
  175. /// Reference to the shader used to display normals.
  176. /// </summary>
  177. private Shader _showNormalsShader;
  178. /// <summary>
  179. /// Reference to the shader used to display metallic.
  180. /// </summary>
  181. private Shader _showMetallicShader;
  182. /// <summary>
  183. /// Reference to the shader used to display smooth.
  184. /// </summary>
  185. private Shader _showSmoothShader;
  186. /// <summary>
  187. /// Reference to the shader used to display albedo.
  188. /// </summary>
  189. private Shader _showAlbedoShader;
  190. /// <summary>
  191. /// Reference to the shader used to display emission.
  192. /// </summary>
  193. private Shader _showEmissionShader;
  194. /// <summary>
  195. /// Reference to the shader used to display occlusion.
  196. /// </summary>
  197. private Shader _showOcclusionShader;
  198. /// <summary>Gets the playing Animation State.</summary>
  199. private AnimationState CurrentAnimationState
  200. {
  201. get
  202. {
  203. if (_animation != null)
  204. {
  205. return _animation[PlaybackAnimation.options[PlaybackAnimation.value].text];
  206. }
  207. return null;
  208. }
  209. }
  210. /// <summary>Is there any animation playing?</summary>
  211. private bool AnimationIsPlaying => _animation != null && _animation.isPlaying;
  212. /// <summary>
  213. /// Shows the file picker for loading a model from the local file-system.
  214. /// </summary>
  215. public void LoadModelFromFile()
  216. {
  217. AssetLoaderOptions.ImportCameras = _loadCamerasToggle.isOn;
  218. AssetLoaderOptions.ImportLights = _loadLightsToggle.isOn;
  219. AssetLoaderOptions.LoadPointClouds = _loadPointClouds.isOn;
  220. base.LoadModelFromFile();
  221. }
  222. /// <summary>
  223. /// Shows the URL selector for loading a model from network.
  224. /// </summary>
  225. public void LoadModelFromURLWithDialogValues()
  226. {
  227. AssetLoaderOptions.ImportCameras = _loadCamerasToggle.isOn;
  228. AssetLoaderOptions.ImportLights = _loadLightsToggle.isOn;
  229. AssetLoaderOptions.LoadPointClouds = _loadPointClouds.isOn;
  230. base.LoadModelFromURLWithDialogValues();
  231. }
  232. /// <summary>Shows the file picker for loading a skybox from the local file-system.</summary>
  233. public void LoadSkyboxFromFile()
  234. {
  235. SetLoading(false);
  236. var title = "Select a skybox image";
  237. var extensions = new ExtensionFilter[]
  238. {
  239. new ExtensionFilter("Radiance HDR Image (hdr)", "hdr")
  240. };
  241. StandaloneFileBrowser.OpenFilePanelAsync(title, null, extensions, true, OnSkyboxStreamSelected);
  242. }
  243. /// <summary>
  244. /// Removes the skybox texture.
  245. /// </summary>
  246. public void ClearSkybox()
  247. {
  248. if (_skyboxMaterial == null)
  249. {
  250. _skyboxMaterial = Instantiate(_skyboxMaterialPreset);
  251. }
  252. _skyboxMaterial.mainTexture = null;
  253. _skyboxExposureSlider.value = 1f;
  254. OnSkyboxExposureChanged(1f);
  255. }
  256. /// <summary>
  257. /// Resets the model scale when loading a new model.
  258. /// </summary>
  259. public void ResetModelScale()
  260. {
  261. if (RootGameObject != null)
  262. {
  263. RootGameObject.transform.localScale = Vector3.one;
  264. }
  265. }
  266. /// <summary>
  267. /// Plays the selected animation.
  268. /// </summary>
  269. public override void PlayAnimation()
  270. {
  271. if (_animation == null)
  272. {
  273. return;
  274. }
  275. _animation.Play(PlaybackAnimation.options[PlaybackAnimation.value].text, PlayMode.StopAll);
  276. }
  277. /// <summary>
  278. /// Stop playing the selected animation.
  279. /// </summary>
  280. public override void StopAnimation()
  281. {
  282. if (_animation == null)
  283. {
  284. return;
  285. }
  286. PlaybackSlider.value = 0f;
  287. _animation.Stop();
  288. SampleAnimationAt(0f);
  289. }
  290. /// <summary>Switches to the animation selected on the Dropdown.</summary>
  291. /// <param name="index">The selected Animation index.</param>
  292. public override void PlaybackAnimationChanged(int index)
  293. {
  294. StopAnimation();
  295. }
  296. /// <summary>Switches to the camera selected on the Dropdown.</summary>
  297. /// <param name="index">The selected Camera index.</param>
  298. public void CameraChanged(int index)
  299. {
  300. for (var i = 0; i < _cameras.Count; i++)
  301. {
  302. var camera = _cameras[i];
  303. camera.enabled = false;
  304. }
  305. if (index == 0)
  306. {
  307. _mainCamera.enabled = true;
  308. }
  309. else
  310. {
  311. _cameras[index - 1].enabled = true;
  312. }
  313. }
  314. /// <summary>Event triggered when the Animation slider value has been changed by the user.</summary>
  315. /// <param name="value">The Animation playback normalized position.</param>
  316. public override void PlaybackSliderChanged(float value)
  317. {
  318. if (!AnimationIsPlaying)
  319. {
  320. var animationState = CurrentAnimationState;
  321. if (animationState != null)
  322. {
  323. SampleAnimationAt(value);
  324. }
  325. }
  326. }
  327. /// <summary>Samples the Animation at the given normalized time.</summary>
  328. /// <param name="value">The Animation normalized time.</param>
  329. private void SampleAnimationAt(float value)
  330. {
  331. if (_animation == null || RootGameObject == null)
  332. {
  333. return;
  334. }
  335. var animationClip = _animation.GetClip(PlaybackAnimation.options[PlaybackAnimation.value].text);
  336. animationClip.SampleAnimation(RootGameObject, animationClip.length * value);
  337. }
  338. /// <summary>
  339. /// Event triggered when the user selects the skybox on the selection dialog.
  340. /// </summary>
  341. /// <param name="files">Selected files.</param>
  342. private void OnSkyboxStreamSelected(IList<ItemWithStream> files)
  343. {
  344. if (files != null && files.Count > 0 && files[0].HasData)
  345. {
  346. Utils.Dispatcher.InvokeAsyncUnchecked(LoadSkybox, files[0].OpenStream());
  347. }
  348. else
  349. {
  350. Utils.Dispatcher.InvokeAsync(ClearSkybox);
  351. }
  352. }
  353. /// <summary>
  354. /// Event triggered when the user changes the debug options dropdown value.
  355. /// </summary>
  356. /// <param name="value">The dropdown value.</param>
  357. public void OnDebugOptionsDropdownChanged(int value)
  358. {
  359. switch (value)
  360. {
  361. default:
  362. if (_showSkeleton != null)
  363. {
  364. _showSkeleton.enabled = value == 1;
  365. }
  366. _mainCamera.ResetReplacementShader();
  367. _mainCamera.renderingPath = RenderingPath.UsePlayerSettings;
  368. break;
  369. case 2:
  370. _mainCamera.SetReplacementShader(_showAlbedoShader, null);
  371. _mainCamera.renderingPath = RenderingPath.Forward;
  372. break;
  373. case 3:
  374. _mainCamera.SetReplacementShader(_showEmissionShader, null);
  375. _mainCamera.renderingPath = RenderingPath.Forward;
  376. break;
  377. case 4:
  378. _mainCamera.SetReplacementShader(_showOcclusionShader, null);
  379. _mainCamera.renderingPath = RenderingPath.Forward;
  380. break;
  381. case 5:
  382. _mainCamera.SetReplacementShader(_showNormalsShader, null);
  383. _mainCamera.renderingPath = RenderingPath.Forward;
  384. break;
  385. case 6:
  386. _mainCamera.SetReplacementShader(_showMetallicShader, null);
  387. _mainCamera.renderingPath = RenderingPath.Forward;
  388. break;
  389. case 7:
  390. _mainCamera.SetReplacementShader(_showSmoothShader, null);
  391. _mainCamera.renderingPath = RenderingPath.Forward;
  392. break;
  393. }
  394. }
  395. /// <summary>Loads the skybox from the given Stream.</summary>
  396. /// <param name="stream">The Stream containing the HDR Image data.</param>
  397. /// <returns>Coroutine IEnumerator.</returns>
  398. private IEnumerator DoLoadSkybox(Stream stream)
  399. {
  400. //Double frame waiting hack
  401. yield return new WaitForEndOfFrame();
  402. yield return new WaitForEndOfFrame();
  403. if (_skyboxTexture != null)
  404. {
  405. Destroy(_skyboxTexture);
  406. }
  407. ClearSkybox();
  408. _skyboxTexture = HDRLoader.HDRLoader.Load(stream, out var gamma, out var exposure);
  409. _skyboxMaterial.mainTexture = _skyboxTexture;
  410. _skyboxExposureSlider.value = 1f;
  411. OnSkyboxExposureChanged(exposure);
  412. stream.Close();
  413. SetLoading(false);
  414. }
  415. /// <summary>Starts the Coroutine to load the skybox from the given Stream.</summary>
  416. /// <param name="stream">The Stream containing the HDR Image data.</param>
  417. private void LoadSkybox(Stream stream)
  418. {
  419. SetLoading(true);
  420. StartCoroutine(DoLoadSkybox(stream));
  421. }
  422. /// <summary>Event triggered when the skybox exposure Slider has changed.</summary>
  423. /// <param name="exposure">The new exposure value.</param>
  424. public void OnSkyboxExposureChanged(float exposure)
  425. {
  426. _skyboxMaterial.SetFloat("_Exposure", exposure);
  427. _skyboxRenderer.material = _skyboxMaterial;
  428. RenderSettings.skybox = _skyboxMaterial;
  429. DynamicGI.UpdateEnvironment();
  430. _reflectionProbe.RenderProbe();
  431. }
  432. /// <summary>Initializes the viewer.</summary>
  433. protected override void Start()
  434. {
  435. base.Start();
  436. if (SystemInfo.deviceType == DeviceType.Handheld)
  437. {
  438. CanvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
  439. }
  440. if (AssetLoaderOptions == null)
  441. {
  442. AssetLoaderOptions = AssetLoader.CreateDefaultLoaderOptions(false, true);
  443. AssetLoaderOptions.Timeout = 160;
  444. AssetLoaderOptions.ShowLoadingWarnings = true;
  445. AssetLoaderOptions.UseUnityNativeTextureLoader = true; // Commenting/removing this line makes TriLib accept more texture file formats, but it will use more memory to load textures.
  446. }
  447. _showNormalsShader = Shader.Find("Hidden/ShowNormals");
  448. _showMetallicShader = Shader.Find("Hidden/ShowMetallic");
  449. _showSmoothShader = Shader.Find("Hidden/ShowSmooth");
  450. _showAlbedoShader = Shader.Find("Hidden/ShowAlbedo");
  451. _showOcclusionShader = Shader.Find("Hidden/ShowOcclusion");
  452. _showEmissionShader = Shader.Find("Hidden/ShowEmission");
  453. ClearSkybox();
  454. InvokeRepeating("ShowMemoryUsage", 0f, 1f);
  455. }
  456. /// <summary>
  457. /// Updates the memory usage text.
  458. /// </summary>
  459. private void ShowMemoryUsage()
  460. {
  461. #if TRILIB_SHOW_MEMORY_USAGE
  462. var memory = RuntimeProcessUtils.GetProcessMemory();
  463. var managedMemory = GC.GetTotalMemory(false);
  464. PeakMemory = Math.Max(memory, PeakMemory);
  465. PeakManagedMemory = Math.Max(managedMemory, PeakManagedMemory);
  466. _memoryUsageText.text = $"(Total: {ProcessUtils.SizeSuffix(memory)} Peak: {ProcessUtils.SizeSuffix(PeakMemory)}) (Managed: {ProcessUtils.SizeSuffix(managedMemory)} Peak: {ProcessUtils.SizeSuffix(PeakManagedMemory)})";
  467. #else
  468. var memory = GC.GetTotalMemory(false);
  469. PeakMemory = Math.Max(memory, PeakMemory);
  470. _memoryUsageText.text = $"Total: {ProcessUtils.SizeSuffix(memory)} Peak: {ProcessUtils.SizeSuffix(PeakMemory)}";
  471. #endif
  472. }
  473. /// <summary>Handles the input.</summary>
  474. private void Update()
  475. {
  476. ProcessInput();
  477. UpdateHUD();
  478. }
  479. /// <summary>Handles the input and moves the Camera accordingly.</summary>
  480. protected virtual void ProcessInput()
  481. {
  482. if (!_mainCamera.enabled)
  483. {
  484. return;
  485. }
  486. ProcessInputInternal(_mainCamera.transform);
  487. }
  488. /// <summary>
  489. /// Handles the input using the given Camera.
  490. /// </summary>
  491. /// <param name="cameraTransform">The Camera to process input movements.</param>
  492. private void ProcessInputInternal(Transform cameraTransform)
  493. {
  494. if (!EventSystem.current.IsPointerOverGameObject())
  495. {
  496. if (GetMouseButton(0))
  497. {
  498. if (GetKey(KeyCode.LeftAlt) || GetKey(KeyCode.RightAlt))
  499. {
  500. _lightAngle.x = Mathf.Repeat(_lightAngle.x + GetAxis("Mouse X"), 360f);
  501. _lightAngle.y = Mathf.Clamp(_lightAngle.y + GetAxis("Mouse Y"), -MaxPitch, MaxPitch);
  502. }
  503. else
  504. {
  505. UpdateCamera();
  506. }
  507. }
  508. if (GetMouseButton(2))
  509. {
  510. CameraPivot -= cameraTransform.up * GetAxis("Mouse Y") * InputMultiplier + cameraTransform.right * GetAxis("Mouse X") * InputMultiplier;
  511. }
  512. CameraDistance = Mathf.Min(CameraDistance - GetMouseScrollDelta().y * InputMultiplier, InputMultiplier * (1f / InputMultiplierRatio) * MaxCameraDistanceRatio);
  513. if (CameraDistance < 0f)
  514. {
  515. CameraPivot += cameraTransform.forward * -CameraDistance;
  516. CameraDistance = 0f;
  517. }
  518. Skybox.transform.position = CameraPivot;
  519. cameraTransform.position = CameraPivot + Quaternion.AngleAxis(CameraAngle.x, Vector3.up) * Quaternion.AngleAxis(CameraAngle.y, Vector3.right) * new Vector3(0f, 0f, Mathf.Max(MinCameraDistance, CameraDistance));
  520. cameraTransform.LookAt(CameraPivot);
  521. _light.transform.position = CameraPivot + Quaternion.AngleAxis(_lightAngle.x, Vector3.up) * Quaternion.AngleAxis(_lightAngle.y, Vector3.right) * Vector3.forward;
  522. _light.transform.LookAt(CameraPivot);
  523. }
  524. }
  525. /// <summary>Updates the HUD information.</summary>
  526. private void UpdateHUD()
  527. {
  528. var animationState = CurrentAnimationState;
  529. var time = animationState == null ? 0f : PlaybackSlider.value * animationState.length % animationState.length;
  530. var seconds = time % 60f;
  531. var milliseconds = time * 100f % 100f;
  532. PlaybackTime.text = $"{seconds:00}:{milliseconds:00}";
  533. var normalizedTime = animationState == null ? 0f : animationState.normalizedTime % 1f;
  534. if (AnimationIsPlaying)
  535. {
  536. PlaybackSlider.value = float.IsNaN(normalizedTime) ? 0f : normalizedTime;
  537. }
  538. var animationIsPlaying = AnimationIsPlaying;
  539. if (_animation != null)
  540. {
  541. Play.gameObject.SetActive(!animationIsPlaying);
  542. Stop.gameObject.SetActive(animationIsPlaying);
  543. }
  544. else
  545. {
  546. Play.gameObject.SetActive(true);
  547. Stop.gameObject.SetActive(false);
  548. PlaybackSlider.value = 0f;
  549. }
  550. }
  551. /// <summary>Event triggered when the user selects a file or cancels the Model selection dialog.</summary>
  552. /// <param name="hasFiles">If any file has been selected, this value is <c>true</c>, otherwise it is <c>false</c>.</param>
  553. protected override void OnBeginLoadModel(bool hasFiles)
  554. {
  555. base.OnBeginLoadModel(hasFiles);
  556. if (hasFiles)
  557. {
  558. if (Application.GetStackTraceLogType(LogType.Exception) != StackTraceLogType.None || Application.GetStackTraceLogType(LogType.Error) != StackTraceLogType.None)
  559. {
  560. _errorPanel.SetActive(false);
  561. }
  562. _animations = null;
  563. _loadingTimeText.text = null;
  564. _stopwatch = new Stopwatch();
  565. _stopwatch.Start();
  566. }
  567. }
  568. /// <summary>Event triggered when the Model Meshes and hierarchy are loaded.</summary>
  569. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  570. protected override void OnLoad(AssetLoaderContext assetLoaderContext)
  571. {
  572. base.OnLoad(assetLoaderContext);
  573. ResetModelScale();
  574. _camerasDropdown.options.Clear();
  575. PlaybackAnimation.options.Clear();
  576. _cameras = null;
  577. _animation = null;
  578. _mainCamera.enabled = true;
  579. if (assetLoaderContext.RootGameObject != null)
  580. {
  581. if (assetLoaderContext.Options.ImportCameras)
  582. {
  583. _cameras = assetLoaderContext.RootGameObject.GetComponentsInChildren<Camera>();
  584. if (_cameras.Count > 0)
  585. {
  586. _camerasDropdown.gameObject.SetActive(true);
  587. _camerasDropdown.options.Add(new Dropdown.OptionData("User Camera"));
  588. for (var i = 0; i < _cameras.Count; i++)
  589. {
  590. var camera = _cameras[i];
  591. camera.enabled = false;
  592. _camerasDropdown.options.Add(new Dropdown.OptionData(camera.name));
  593. }
  594. _camerasDropdown.captionText.text = _cameras[0].name;
  595. }
  596. else
  597. {
  598. _cameras = null;
  599. }
  600. }
  601. _animation = assetLoaderContext.RootGameObject.GetComponent<Animation>();
  602. if (_animation != null)
  603. {
  604. _animations = _animation.GetAllAnimationClips();
  605. if (_animations.Count > 0)
  606. {
  607. PlaybackAnimation.interactable = true;
  608. for (var i = 0; i < _animations.Count; i++)
  609. {
  610. var animationClip = _animations[i];
  611. PlaybackAnimation.options.Add(new Dropdown.OptionData(animationClip.name));
  612. }
  613. PlaybackAnimation.captionText.text = _animations[0].name;
  614. }
  615. else
  616. {
  617. _animation = null;
  618. }
  619. }
  620. _camerasDropdown.value = 0;
  621. PlaybackAnimation.value = 0;
  622. StopAnimation();
  623. RootGameObject = assetLoaderContext.RootGameObject;
  624. }
  625. if (_cameras == null)
  626. {
  627. _camerasDropdown.gameObject.SetActive(false);
  628. }
  629. if (_animation == null)
  630. {
  631. PlaybackAnimation.interactable = false;
  632. PlaybackAnimation.captionText.text = "No Animations";
  633. }
  634. ModelTransformChanged();
  635. }
  636. /// <summary>
  637. /// Fits the camera into a custom given bounds.
  638. /// </summary>
  639. /// <param name="bounds">The bounds to fit the camera to.</param>
  640. public void SetCustomBounds(Bounds bounds)
  641. {
  642. _mainCamera.FitToBounds(bounds, CameraDistanceRatio);
  643. CameraDistance = _mainCamera.transform.position.magnitude;
  644. CameraPivot = bounds.center;
  645. Skybox.transform.localScale = bounds.size.magnitude * SkyboxScale * Vector3.one;
  646. InputMultiplier = bounds.size.magnitude * InputMultiplierRatio;
  647. CameraAngle = Vector2.zero;
  648. }
  649. /// <summary>
  650. /// Changes the camera placement when the Model has changed.
  651. /// </summary>
  652. protected virtual void ModelTransformChanged()
  653. {
  654. if (RootGameObject != null && _mainCamera.enabled)
  655. {
  656. var bounds = RootGameObject.CalculateBounds();
  657. _mainCamera.FitToBounds(bounds, CameraDistanceRatio);
  658. // Uncomment this code to scale up small objects
  659. //if (bounds.size.magnitude < 1f)
  660. //{
  661. // var increase = 1f / bounds.size.magnitude;
  662. // RootGameObject.transform.localScale *= increase;
  663. // bounds = RootGameObject.CalculateBounds();
  664. //}
  665. CameraDistance = _mainCamera.transform.position.magnitude;
  666. CameraPivot = bounds.center;
  667. Skybox.transform.localScale = bounds.size.magnitude * SkyboxScale * Vector3.one;
  668. InputMultiplier = bounds.size.magnitude * InputMultiplierRatio;
  669. CameraAngle = Vector2.zero;
  670. }
  671. }
  672. /// <summary>
  673. /// Event is triggered when any error occurs.
  674. /// </summary>
  675. /// <param name="contextualizedError">The Contextualized Error that has occurred.</param>
  676. protected override void OnError(IContextualizedError contextualizedError)
  677. {
  678. if (Application.GetStackTraceLogType(LogType.Exception) != StackTraceLogType.None || Application.GetStackTraceLogType(LogType.Error) != StackTraceLogType.None)
  679. {
  680. _errorPanelText.text = contextualizedError.ToString();
  681. _errorPanel.SetActive(true);
  682. }
  683. base.OnError(contextualizedError);
  684. StopAnimation();
  685. }
  686. /// <summary>Event is triggered when the Model (including Textures and Materials) has been fully loaded.</summary>
  687. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  688. protected override void OnMaterialsLoad(AssetLoaderContext assetLoaderContext)
  689. {
  690. base.OnMaterialsLoad(assetLoaderContext);
  691. _stopwatch.Stop();
  692. _loadingTimeText.text = $"Loaded in: {_stopwatch.Elapsed.Minutes:00}:{_stopwatch.Elapsed.Seconds:00}";
  693. ModelTransformChanged();
  694. if (assetLoaderContext.RootGameObject != null)
  695. {
  696. _showSkeleton = assetLoaderContext.RootGameObject.AddComponent<ShowSkeleton>();
  697. _showSkeleton.Setup(assetLoaderContext, this);
  698. assetLoaderContext.Allocations.Add(_showSkeleton);
  699. if (assetLoaderContext.Options.LoadPointClouds && assetLoaderContext.RootGameObject != null)
  700. {
  701. HandlePointClouds(assetLoaderContext);
  702. }
  703. var meshAllocation = 0;
  704. var textureAllocation = 0;
  705. var materialAllocation = 0;
  706. var animationClipAllocation = 0;
  707. var miscAllocation = 0;
  708. foreach (var allocation in assetLoaderContext.Allocations)
  709. {
  710. var runtimeMemorySize = Profiler.GetRuntimeMemorySize(allocation);
  711. if (allocation is Mesh)
  712. {
  713. meshAllocation += runtimeMemorySize;
  714. }
  715. else if (allocation is Texture)
  716. {
  717. textureAllocation += runtimeMemorySize;
  718. }
  719. else if (allocation is Material)
  720. {
  721. materialAllocation += runtimeMemorySize;
  722. }
  723. else if (allocation is AnimationClip)
  724. {
  725. animationClipAllocation += runtimeMemorySize;
  726. }
  727. else
  728. {
  729. miscAllocation += runtimeMemorySize;
  730. }
  731. }
  732. _usedMemoryText.text = UnityEngine.Debug.isDebugBuild ? $"Used Memory:\nMeshes: {ProcessUtils.SizeSuffix(meshAllocation)}\nTextures: {ProcessUtils.SizeSuffix(textureAllocation)}\nMaterials: {ProcessUtils.SizeSuffix(materialAllocation)}\nAnimation Clips: {ProcessUtils.SizeSuffix(animationClipAllocation)}\nMisc.: {ProcessUtils.SizeSuffix(miscAllocation)}" : string.Empty;
  733. }
  734. else
  735. {
  736. _usedMemoryText.text = string.Empty;
  737. }
  738. OnDebugOptionsDropdownChanged(_debugOptionsDropdown.value);
  739. }
  740. /// <summary>Handles Point Clouds rendering.</summary>
  741. /// <param name="assetLoaderContext">The Asset Loader Context reference. Asset Loader Context contains the Model loading data.</param>
  742. private void HandlePointClouds(AssetLoaderContext assetLoaderContext)
  743. {
  744. Material material = null;
  745. foreach (var gameObject in assetLoaderContext.GameObjects.Values)
  746. {
  747. if (gameObject.TryGetComponent<MeshFilter>(out var meshFilter))
  748. {
  749. var points = meshFilter.sharedMesh.vertices;
  750. var colors = meshFilter.sharedMesh.colors32;
  751. if (colors == null || colors.Length != points.Length)
  752. {
  753. colors = new Color32[points.Length];
  754. for (var i = 0; i < colors.Length; i++)
  755. {
  756. colors[i] = Color.white;
  757. }
  758. }
  759. if (SystemInfo.graphicsDeviceType != GraphicsDeviceType.Direct3D11 && SystemInfo.graphicsDeviceType != GraphicsDeviceType.Direct3D12)
  760. {
  761. var mesh = new Mesh();
  762. mesh.indexFormat = IndexFormat.UInt32;
  763. mesh.SetVertices(points);
  764. mesh.SetColors(colors);
  765. mesh.SetIndices(
  766. Enumerable.Range(0, points.Length).ToArray(),
  767. MeshTopology.Points, 0
  768. );
  769. mesh.UploadMeshData(!assetLoaderContext.Options.ReadEnabled);
  770. meshFilter.sharedMesh = mesh;
  771. var meshRenderer = gameObject.AddComponent<MeshRenderer>();
  772. var materials = new Material[meshFilter.sharedMesh.subMeshCount];
  773. if (material == null)
  774. {
  775. material = new Material(Shader.Find("Hidden/PointCloud_GL"));
  776. }
  777. for (var i = 0; i < materials.Length; i++)
  778. {
  779. materials[i] = material;
  780. }
  781. meshRenderer.materials = materials;
  782. }
  783. else
  784. {
  785. var pointCloudRenderer = assetLoaderContext.RootGameObject.AddComponent<PointCloudRenderer>();
  786. var data = ScriptableObject.CreateInstance<PointCloudData>();
  787. data.Initialize(points, colors);
  788. pointCloudRenderer.sourceData = data;
  789. pointCloudRenderer.destroyData = true;
  790. pointCloudRenderer.pointSize = 0.01f;
  791. assetLoaderContext.Allocations.Add(data);
  792. }
  793. }
  794. }
  795. }
  796. }
  797. }