BoneWeightExtensions.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using UnityEngine;
  3. namespace UnityEditor.U2D.Animation
  4. {
  5. internal static class BoneWeightExtensions
  6. {
  7. public static int GetBoneIndex(this BoneWeight boneWeight, int channelIndex)
  8. {
  9. if (channelIndex < 0 || channelIndex >= 4)
  10. throw new ArgumentOutOfRangeException("Channel index out of range");
  11. if (channelIndex == 0)
  12. return boneWeight.boneIndex0;
  13. if (channelIndex == 1)
  14. return boneWeight.boneIndex1;
  15. if (channelIndex == 2)
  16. return boneWeight.boneIndex2;
  17. if (channelIndex == 3)
  18. return boneWeight.boneIndex3;
  19. return -1;
  20. }
  21. public static void SetBoneIndex(ref BoneWeight boneWeight, int channelIndex, int boneIndex)
  22. {
  23. if (channelIndex < 0 || channelIndex >= 4)
  24. throw new ArgumentOutOfRangeException("Channel index out of range");
  25. if (channelIndex == 0)
  26. boneWeight.boneIndex0 = boneIndex;
  27. if (channelIndex == 1)
  28. boneWeight.boneIndex1 = boneIndex;
  29. if (channelIndex == 2)
  30. boneWeight.boneIndex2 = boneIndex;
  31. if (channelIndex == 3)
  32. boneWeight.boneIndex3 = boneIndex;
  33. }
  34. public static float GetWeight(this BoneWeight boneWeight, int channelIndex)
  35. {
  36. if (channelIndex < 0 || channelIndex >= 4)
  37. throw new ArgumentOutOfRangeException("Channel index out of range");
  38. if (channelIndex == 0)
  39. return boneWeight.weight0;
  40. if (channelIndex == 1)
  41. return boneWeight.weight1;
  42. if (channelIndex == 2)
  43. return boneWeight.weight2;
  44. if (channelIndex == 3)
  45. return boneWeight.weight3;
  46. return 0f;
  47. }
  48. public static void SetWeight(ref BoneWeight boneWeight, int channelIndex, float weight)
  49. {
  50. if (channelIndex < 0 || channelIndex >= 4)
  51. throw new ArgumentOutOfRangeException("Channel index out of range");
  52. if (channelIndex == 0)
  53. boneWeight.weight0 = weight;
  54. if (channelIndex == 1)
  55. boneWeight.weight1 = weight;
  56. if (channelIndex == 2)
  57. boneWeight.weight2 = weight;
  58. if (channelIndex == 3)
  59. boneWeight.weight3 = weight;
  60. }
  61. public static float Sum(this BoneWeight boneWeight)
  62. {
  63. return boneWeight.weight0 + boneWeight.weight1 + boneWeight.weight2 + boneWeight.weight3;
  64. }
  65. public static BoneWeight Normalized(this BoneWeight boneWeight)
  66. {
  67. var sum = boneWeight.Sum();
  68. if (sum == 0 || sum == 1f)
  69. return boneWeight;
  70. var normalized = boneWeight;
  71. var sumInv = 1f / sum;
  72. for (var i = 0; i < 4; ++i)
  73. SetWeight(ref normalized, i, normalized.GetWeight(i) * sumInv);
  74. return normalized;
  75. }
  76. }
  77. }