From 61fdf43488e393adfb538724002e690c89231f12 Mon Sep 17 00:00:00 2001 From: Danilo Date: Sat, 18 May 2024 10:24:26 -0300 Subject: [PATCH] Implementa Ray --- framework/common/collision.cpp | 18 ++++++++++++++++++ inc/common/collision.hpp | 27 ++++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/framework/common/collision.cpp b/framework/common/collision.cpp index f6b1460..b4ddf53 100644 --- a/framework/common/collision.cpp +++ b/framework/common/collision.cpp @@ -38,6 +38,24 @@ namespace xna { return p; } + std::optional Plane::Intersects(Ray const& ray) const { + const auto num1 = (Normal.X * ray.Direction.X + Normal.Y * ray.Direction.Y + Normal.Z * ray.Direction.Z); + + if (std::abs(num1) < 9.9999997473787516E-06) + return {}; + + const auto num2 = (Normal.X * ray.Position.X + Normal.Y * ray.Position.Y + Normal.Z * ray.Position.Z); + auto num3 = (-D - num2) / num1; + + if (num3 < 0.0) + { + if (num3 < -9.9999997473787516E-06) + return {}; + num3 = 0.0f; + } + + return num3; + } bool BoundingFrustum::Intersects(BoundingBox const& box) { gjk.Reset(); diff --git a/inc/common/collision.hpp b/inc/common/collision.hpp index 121daaa..8ebc624 100644 --- a/inc/common/collision.hpp +++ b/inc/common/collision.hpp @@ -41,6 +41,7 @@ namespace xna { constexpr PlaneIntersectionType Intersects(BoundingBox const& box) const; constexpr PlaneIntersectionType Intersects(BoundingFrustum const& frustum) const; constexpr PlaneIntersectionType Intersects(BoundingSphere const& sphere) const; + std::optional Intersects(Ray const& ray) const; }; struct BoundingFrustum { @@ -166,6 +167,30 @@ namespace xna { struct Ray { Vector3 Position{}; Vector3 Direction{}; + + constexpr Ray() = default; + constexpr Ray(Vector3 const& position, Vector3 const& direction): + Position(position), Direction(direction){} + + constexpr bool operator==(Ray const& other) const { + return Position == other.Position && Direction == other.Direction; + } + + std::optional Intersects(BoundingBox const& box) const { + return box.Intersects(*this); + } + + std::optional Intersects(BoundingFrustum const& frustum) const { + return frustum.Intersects(*this); + } + + std::optional Intersects(Plane const& plane) const { + return plane.Intersects(*this); + } + + std::optional Sphere(BoundingSphere const& sphere) const { + return sphere.Intersects(*this); + } }; //---------------------------------------------------------------------------------// @@ -570,7 +595,7 @@ namespace xna { return num < -sphere.Radius ? PlaneIntersectionType::Back : PlaneIntersectionType::Intersecting; - } + } } #endif \ No newline at end of file