UnsafeAnimationCurve.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using Unity.Collections;
  3. using Unity.Collections.LowLevel.Unsafe;
  4. using UnityEngine;
  5. // TODO: avoid animationCurve.keys allocation
  6. namespace LitMotion.Collections
  7. {
  8. public unsafe struct UnsafeAnimationCurve : IDisposable
  9. {
  10. internal UnsafeList<Keyframe> keys;
  11. internal WrapMode preWrapMode;
  12. internal WrapMode postWrapMode;
  13. public UnsafeAnimationCurve(AllocatorManager.AllocatorHandle allocator)
  14. {
  15. keys = new UnsafeList<Keyframe>(0, allocator);
  16. preWrapMode = default;
  17. postWrapMode = default;
  18. }
  19. public UnsafeAnimationCurve(AnimationCurve animationCurve, AllocatorManager.AllocatorHandle allocator)
  20. {
  21. var l = animationCurve.length;
  22. keys = new UnsafeList<Keyframe>(l, allocator);
  23. keys.Resize(l, NativeArrayOptions.UninitializedMemory);
  24. fixed (Keyframe* src = &animationCurve.keys[0])
  25. {
  26. UnsafeUtility.MemCpy(keys.Ptr, src, l * sizeof(Keyframe));
  27. }
  28. keys.Sort(default(KeyframeComparer));
  29. preWrapMode = animationCurve.preWrapMode;
  30. postWrapMode = animationCurve.postWrapMode;
  31. }
  32. public void CopyFrom(AnimationCurve animationCurve)
  33. {
  34. var l = animationCurve.length;
  35. keys.Resize(l, NativeArrayOptions.UninitializedMemory);
  36. fixed (Keyframe* src = &animationCurve.keys[0])
  37. {
  38. UnsafeUtility.MemCpy(keys.Ptr, src, l * sizeof(Keyframe));
  39. }
  40. keys.Sort(default(KeyframeComparer));
  41. preWrapMode = animationCurve.preWrapMode;
  42. postWrapMode = animationCurve.postWrapMode;
  43. }
  44. public void CopyFrom(in UnsafeAnimationCurve animationCurve)
  45. {
  46. keys.CopyFrom(animationCurve.keys);
  47. preWrapMode = animationCurve.preWrapMode;
  48. postWrapMode = animationCurve.postWrapMode;
  49. }
  50. public void Dispose()
  51. {
  52. keys.Dispose();
  53. }
  54. public readonly bool IsCreated => keys.IsCreated;
  55. public float Evaluate(float time)
  56. {
  57. return NativeAnimationCurveHelper.Evaluate(keys.Ptr, keys.Length, preWrapMode, postWrapMode, time);
  58. }
  59. }
  60. }