AnimatableProperty.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace MonoScene.Graphics.Content
  7. {
  8. /// <summary>
  9. /// Defines an animatable property with a default value and a collection of animation curve tracks.
  10. /// </summary>
  11. /// <typeparam name="T">A type that can be interpolated with <see cref="ICurveEvaluator{T}"/></typeparam>
  12. [System.Diagnostics.DebuggerDisplay("{Value} with {CurveCount} curves.")]
  13. public sealed class AnimatableProperty<T>
  14. where T : struct
  15. {
  16. #region lifecycle
  17. public AnimatableProperty(T defaultValue)
  18. {
  19. Value = defaultValue;
  20. }
  21. #endregion
  22. #region data
  23. private List<Microsoft.Xna.Framework.ICurveEvaluator<T>> _Curves;
  24. /// <summary>
  25. /// Gets the default value of this instance.
  26. /// When animations are disabled, or there's no animation track available, this will be the returned value.
  27. /// </summary>
  28. public T Value { get; set; }
  29. #endregion
  30. #region properties
  31. public bool IsAnimated => _Curves == null ? false : _Curves.Count > 0;
  32. public int CurveCount => _Curves.Count;
  33. #endregion
  34. #region API
  35. /// <summary>
  36. /// Evaluates the value of this <see cref="AnimatableProperty{T}"/> at a given <paramref name="offset"/> for a given <paramref name="curveIndex"/>.
  37. /// </summary>
  38. /// <param name="curveIndex">The index of the animation track</param>
  39. /// <param name="offset">The time offset within the curve</param>
  40. /// <returns>The evaluated value taken from the animation <paramref name="curveIndex"/>, or <see cref="Value"/> if a track was not found.</returns>
  41. public T GetValueAt(int curveIndex, float offset)
  42. {
  43. if (_Curves == null) return this.Value;
  44. if (curveIndex < 0 || curveIndex >= _Curves.Count) return this.Value;
  45. return _Curves[curveIndex]?.Evaluate(offset) ?? this.Value;
  46. }
  47. public void SetCurve(int curveIndex, Microsoft.Xna.Framework.ICurveEvaluator<T> sampler)
  48. {
  49. if (curveIndex < 0) throw new ArgumentOutOfRangeException(nameof(curveIndex));
  50. if (_Curves == null) _Curves = new List<Microsoft.Xna.Framework.ICurveEvaluator<T>>();
  51. while (_Curves.Count <= curveIndex) _Curves.Add(null);
  52. _Curves[curveIndex] = sampler ?? throw new ArgumentNullException(nameof(sampler));
  53. }
  54. #endregion
  55. }
  56. }