LinearOperations.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System;
  2. using System.Linq.Expressions;
  3. namespace MonoGame.Extended.Tweening;
  4. /// <summary>
  5. /// Provides compiled arithmetic delegates for a value type <typeparamref name="T"/>, enabling
  6. /// type-agnostic linear interpolation over any struct that supports addition, subtraction, and
  7. /// scalar multiplication operators. The delegates are compiled once via expression trees and
  8. /// cached as static members.
  9. /// </summary>
  10. /// <typeparam name="T">
  11. /// The value type to compile operations for. Must define <c>+</c>, <c>-</c>, and <c>*</c>
  12. /// operators, with <c>*</c> accepting a <see cref="float"/> scalar as the right-hand operand.
  13. /// </typeparam>
  14. public class LinearOperations<T>
  15. {
  16. static LinearOperations()
  17. {
  18. var a = Expression.Parameter(typeof(T));
  19. var b = Expression.Parameter(typeof(T));
  20. var c = Expression.Parameter(typeof(float));
  21. Add = Expression.Lambda<Func<T, T, T>>(Expression.Add(a, b), a, b).Compile();
  22. Subtract = Expression.Lambda<Func<T, T, T>>(Expression.Subtract(a, b), a, b).Compile();
  23. Multiply = Expression.Lambda<Func<T, float, T>>(Expression.Multiply(a, c), a, c).Compile();
  24. }
  25. /// <summary>
  26. /// Gets a compiled delegate that adds two values of type <typeparamref name="T"/>.
  27. /// </summary>
  28. public static Func<T, T, T> Add { get; }
  29. /// <summary>
  30. /// Gets a compiled delegate that subtracts the second value from the first for type <typeparamref name="T"/>.
  31. /// </summary>
  32. public static Func<T, T, T> Subtract { get; }
  33. /// <summary>
  34. /// Gets a compiled delegate that multiplies a value of type <typeparamref name="T"/> by a <see cref="float"/> scalar.
  35. /// </summary>
  36. public static Func<T, float, T> Multiply { get; }
  37. }