RayCast.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Physics/Collision/BackFaceMode.h>
  6. JPH_NAMESPACE_BEGIN
  7. /// Structure that holds a single ray cast
  8. template <class Vec, class Mat, class RayCastType>
  9. struct RayCastT
  10. {
  11. JPH_OVERRIDE_NEW_DELETE
  12. /// Constructors
  13. RayCastT() = default; // Allow raycast to be created uninitialized
  14. RayCastT(typename Vec::ArgType inOrigin, Vec3Arg inDirection) : mOrigin(inOrigin), mDirection(inDirection) { }
  15. RayCastT(const RayCastT<Vec, Mat, RayCastType> &) = default;
  16. /// Transform this ray using inTransform
  17. RayCastType Transformed(typename Mat::ArgType inTransform) const
  18. {
  19. Vec ray_origin = inTransform * mOrigin;
  20. Vec3 ray_direction(inTransform * (mOrigin + mDirection) - ray_origin);
  21. return { ray_origin, ray_direction };
  22. }
  23. /// Translate ray using inTranslation
  24. RayCastType Translated(typename Vec::ArgType inTranslation) const
  25. {
  26. return { inTranslation + mOrigin, mDirection };
  27. }
  28. /// Get point with fraction inFraction on ray (0 = start of ray, 1 = end of ray)
  29. inline Vec GetPointOnRay(float inFraction) const
  30. {
  31. return mOrigin + inFraction * mDirection;
  32. }
  33. Vec mOrigin; ///< Origin of the ray
  34. Vec3 mDirection; ///< Direction and length of the ray (anything beyond this length will not be reported as a hit)
  35. };
  36. struct RayCast : public RayCastT<Vec3, Mat44, RayCast>
  37. {
  38. using RayCastT<Vec3, Mat44, RayCast>::RayCastT;
  39. };
  40. struct RRayCast : public RayCastT<RVec3, RMat44, RRayCast>
  41. {
  42. using RayCastT<RVec3, RMat44, RRayCast>::RayCastT;
  43. /// Convert from RayCast, converts single to double precision
  44. explicit RRayCast(const RayCast &inRay) :
  45. RRayCast(RVec3(inRay.mOrigin), inRay.mDirection)
  46. {
  47. }
  48. /// Convert to RayCast, which implies casting from double precision to single precision
  49. explicit operator RayCast() const
  50. {
  51. return RayCast(Vec3(mOrigin), mDirection);
  52. }
  53. };
  54. /// Settings to be passed with a ray cast
  55. class RayCastSettings
  56. {
  57. public:
  58. JPH_OVERRIDE_NEW_DELETE
  59. /// How backfacing triangles should be treated
  60. EBackFaceMode mBackFaceMode = EBackFaceMode::IgnoreBackFaces;
  61. /// If convex shapes should be treated as solid. When true, a ray starting inside a convex shape will generate a hit at fraction 0.
  62. bool mTreatConvexAsSolid = true;
  63. };
  64. JPH_NAMESPACE_END