ShowSkeleton.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System.Collections.Generic;
  2. using TriLibCore.Extensions;
  3. using UnityEngine;
  4. namespace TriLibCore.Samples
  5. {
  6. public class ShowSkeleton : MonoBehaviour
  7. {
  8. private List<Transform> _bones;
  9. private static Material _material;
  10. public void Setup(AssetLoaderContext assetLoaderContext, AssetViewer assetViewer)
  11. {
  12. if (_material == null)
  13. {
  14. _material = new Material(Shader.Find("Hidden/ShowSkeleton"));
  15. }
  16. _bones = new List<Transform>();
  17. assetLoaderContext.RootModel.GetBones(assetLoaderContext, _bones);
  18. if (_bones.Count > 0)
  19. {
  20. SetCustomBounds(assetLoaderContext, assetViewer);
  21. }
  22. }
  23. private void SetCustomBounds(AssetLoaderContext assetLoaderContext, AssetViewer assetViewer)
  24. {
  25. var totalBounds = new Bounds();
  26. var totalBoundsInitialized = false;
  27. if (assetViewer.RootGameObject.TryGetComponent<Animation>(out var animation))
  28. {
  29. var animationClips = animation.GetAllAnimationClips();
  30. foreach (var clip in animationClips)
  31. {
  32. animation.clip = clip;
  33. var frameInterval = 1f / clip.frameRate;
  34. for (var t = 0f; t < clip.length; t += frameInterval)
  35. {
  36. animation[clip.name].time = t;
  37. animation.Sample();
  38. var bounds = new Bounds();
  39. var initialized = false;
  40. foreach (var bone in _bones)
  41. {
  42. if (!initialized)
  43. {
  44. bounds.center = bone.position;
  45. if (!totalBoundsInitialized)
  46. {
  47. totalBounds.center = bone.position;
  48. totalBoundsInitialized = true;
  49. }
  50. initialized = true;
  51. }
  52. else
  53. {
  54. bounds.Encapsulate(bone.position);
  55. }
  56. }
  57. totalBounds.Encapsulate(bounds);
  58. }
  59. }
  60. }
  61. if (totalBounds.size.magnitude > 0f)
  62. {
  63. assetViewer.SetCustomBounds(totalBounds);
  64. }
  65. }
  66. private void OnRenderObject()
  67. {
  68. _material.SetPass(0);
  69. GL.PushMatrix();
  70. GL.Begin(GL.LINES);
  71. foreach (var transform in _bones)
  72. {
  73. foreach (Transform child in transform)
  74. {
  75. GL.Color(Color.green);
  76. GL.Vertex(transform.position);
  77. GL.Vertex(child.position);
  78. }
  79. }
  80. GL.End();
  81. GL.PopMatrix();
  82. }
  83. }
  84. }