AssetViewer.cs 31 KB

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