diff --git a/Source/Engine/Core/Math/CollisionsHelper.cpp b/Source/Engine/Core/Math/CollisionsHelper.cpp index f778fa4ec..48e262286 100644 --- a/Source/Engine/Core/Math/CollisionsHelper.cpp +++ b/Source/Engine/Core/Math/CollisionsHelper.cpp @@ -1437,6 +1437,16 @@ bool CollisionsHelper::LineIntersectsRect(const Vector2& p1, const Vector2& p2, return (topoverlap < botoverlap) && (!((botoverlap < t) || (topoverlap > b)));*/ } +Vector2 CollisionsHelper::LineHitsBox(const Vector3& lineStart, const Vector3& lineEnd, const Vector3& boxMin, const Vector3& boxMax) +{ + const Vector3 invDirection = 1.0f / (lineEnd - lineStart); + const Vector3 enterIntersection = (boxMin - lineStart) * invDirection; + const Vector3 exitIntersection = (boxMax - lineStart) * invDirection; + const Vector3 minIntersections = Vector3::Min(enterIntersection, exitIntersection); + const Vector3 maxIntersections = Vector3::Max(enterIntersection, exitIntersection); + return Vector2(Math::Saturate(minIntersections.MaxValue()), Math::Saturate(maxIntersections.MinValue())); +} + bool CollisionsHelper::IsPointInTriangle(const Vector2& point, const Vector2& a, const Vector2& b, const Vector2& c) { const Vector2 an = a - point; diff --git a/Source/Engine/Core/Math/CollisionsHelper.h b/Source/Engine/Core/Math/CollisionsHelper.h index 9720369c1..ef1791ec1 100644 --- a/Source/Engine/Core/Math/CollisionsHelper.h +++ b/Source/Engine/Core/Math/CollisionsHelper.h @@ -569,6 +569,12 @@ public: /// True if line intersects with the rectangle static bool LineIntersectsRect(const Vector2& p1, const Vector2& p2, const Rectangle& rect); + // Hits axis-aligned box (boxMin, boxMax) with a line (lineStart, lineEnd). + // Returns the intersections on the line (x - closest, y - furthest). + // Line hits the box if: intersections.x < intersections.y. + // Hit point is: hitPoint = lineStart + (lineEnd - lineStart) * intersections.x/y. + static Vector2 LineHitsBox(const Vector3& lineStart, const Vector3& lineEnd, const Vector3& boxMin, const Vector3& boxMax); + /// /// Determines whether the given 2D point is inside the specified triangle. /// diff --git a/Source/Shaders/Math.hlsl b/Source/Shaders/Math.hlsl index 0299ebf6d..037efccba 100644 --- a/Source/Shaders/Math.hlsl +++ b/Source/Shaders/Math.hlsl @@ -54,6 +54,21 @@ float4 Square(float4 x) return x * x; } +float Min2(float2 x) +{ + return min(x.x, x.y); +} + +float Min3(float3 x) +{ + return min(x.x, min(x.y, x.z)); +} + +float Min4(float4 x) +{ + return min(x.x, min(x.y, min(x.z, x.w))); +} + float Max2(float2 x) { return max(x.x, x.y);