Ray.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. namespace BansheeEngine
  7. {
  8. /// <summary>
  9. /// A ray in 3D space represented with an origin and direction.
  10. /// </summary>
  11. [StructLayout(LayoutKind.Sequential), SerializeObject]
  12. public struct Ray // Note: Must match C++ struct Ray
  13. {
  14. public Vector3 origin;
  15. public Vector3 direction;
  16. /// <summary>
  17. /// Creates a new ray.
  18. /// </summary>
  19. /// <param name="origin">Coordinates for the origin of the ray.</param>
  20. /// <param name="direction">Normalized direction of the ray.</param>
  21. public Ray(Vector3 origin, Vector3 direction)
  22. {
  23. this.origin = origin;
  24. this.direction = direction;
  25. }
  26. /// <summary>
  27. /// Multiples ray by a scalar and retrieves a point along the ray.
  28. /// </summary>
  29. /// <param name="ray">Ray to transform.</param>
  30. /// <param name="t">How far along the ray to retrieve the point.</param>
  31. /// <returns>Point along the ray <paramref name="t"/> units away from the origin.</returns>
  32. public static Vector3 operator*(Ray ray, float t)
  33. {
  34. return ray.origin + ray.direction * t;
  35. }
  36. /// <summary>
  37. /// Transforms the ray by the specified matrix. If the matrix is affine use
  38. /// <see cref="TransformAffine"/> as it is faster.
  39. /// </summary>
  40. /// <param name="matrix">Matrix to transform the ray by.</param>
  41. public void Transform(Matrix4 matrix)
  42. {
  43. Vector3 end = this * 1.0f;
  44. origin = matrix.Multiply(origin);
  45. end = matrix.Multiply(end);
  46. direction = Vector3.Normalize(end - origin);
  47. }
  48. /// <summary>
  49. /// Transforms the ray by the specified affine matrix.
  50. /// </summary>
  51. /// <param name="matrix">Affine matrix to transform the ray by.</param>
  52. public void TransformAffine(Matrix4 matrix)
  53. {
  54. Vector3 end = this * 1.0f;
  55. origin = matrix.MultiplyDirection(origin);
  56. end = matrix.MultiplyDirection(end);
  57. direction = Vector3.Normalize(end - origin);
  58. }
  59. /// <inheritdoc/>
  60. public override string ToString()
  61. {
  62. return String.Format("(origin: {0} direction: {1})", origin, direction);
  63. }
  64. };
  65. }