Added Capsule Collider, AABB Query & SimulateBody for Trajectory path prediction #402

Merged
direnbharwani merged 13 commits from SP3-2-Physics into main 2023-03-07 20:11:22 +08:00
32 changed files with 1337 additions and 132 deletions

View File

@ -5,13 +5,14 @@
Components: Components:
Transform Component: Transform Component:
Translate: {x: 0, y: 7, z: 0} Translate: {x: 0, y: 7, z: 0}
Rotate: {x: 1.48352981, y: 0, z: 0} Rotate: {x: 0, y: 0, z: 0}
Scale: {x: 0.999999344, y: 0.999999821, z: 0.999999523} Scale: {x: 0.999999344, y: 0.999999821, z: 0.999999523}
IsActive: true IsActive: true
RigidBody Component: RigidBody Component:
Type: Dynamic Type: Dynamic
Drag: 0.00999999978 Drag: 0.00999999978
Angular Drag: 0.100000001 Angular Drag: 0.100000001
Gravity Scale: 1
Use Gravity: true Use Gravity: true
Interpolate: false Interpolate: false
Sleeping Enabled: true Sleeping Enabled: true
@ -26,8 +27,9 @@
Colliders: Colliders:
- Is Trigger: false - Is Trigger: false
Collision Tag: 0 Collision Tag: 0
Type: Box Type: Capsule
Half Extents: {x: 1, y: 1, z: 1} Radius: 1
Height: 2
Friction: 0.400000006 Friction: 0.400000006
Bounciness: 0 Bounciness: 0
Density: 1 Density: 1
@ -75,10 +77,10 @@
Yaw: 0 Yaw: 0
Roll: 0 Roll: 0
Width: 1920 Width: 1920
Height: 1080
Near: 0.00999999978 Near: 0.00999999978
Far: 10000 Far: 10000
Perspective: true Perspective: true
FOV: 90
IsActive: true IsActive: true
Scripts: ~ Scripts: ~
- EID: 65539 - EID: 65539
@ -187,6 +189,7 @@
Type: Dynamic Type: Dynamic
Drag: 0.00999999978 Drag: 0.00999999978
Angular Drag: 0.100000001 Angular Drag: 0.100000001
Gravity Scale: 1
Use Gravity: true Use Gravity: true
Interpolate: true Interpolate: true
Sleeping Enabled: true Sleeping Enabled: true

View File

@ -9,9 +9,7 @@
namespace SHADE namespace SHADE
{ {
struct SHRay;
class SHBox;
class SHRay;
class SH_API SHCameraArmComponent final: public SHComponent class SH_API SHCameraArmComponent final: public SHComponent
{ {

View File

@ -15,6 +15,7 @@
#include "Editor/SHEditorWidgets.hpp" #include "Editor/SHEditorWidgets.hpp"
#include "Graphics/MiddleEnd/Interface/SHRenderable.h" #include "Graphics/MiddleEnd/Interface/SHRenderable.h"
#include "Graphics/MiddleEnd/Lights/SHLightComponent.h" #include "Graphics/MiddleEnd/Lights/SHLightComponent.h"
#include "Physics/Interface/SHRigidBodyComponent.h"
#include "Physics/Interface/SHColliderComponent.h" #include "Physics/Interface/SHColliderComponent.h"
#include "Reflection/SHReflectionMetadata.h" #include "Reflection/SHReflectionMetadata.h"
#include "Resource/SHResourceManager.h" #include "Resource/SHResourceManager.h"
@ -25,6 +26,7 @@
#include "Animation/SHAnimatorComponent.h" #include "Animation/SHAnimatorComponent.h"
#include "Physics/Collision/Shapes/SHBox.h" #include "Physics/Collision/Shapes/SHBox.h"
#include "Physics/Collision/Shapes/SHSphere.h" #include "Physics/Collision/Shapes/SHSphere.h"
#include "Physics/Collision/Shapes/SHCapsule.h"
#include "../SHEditorWindowManager.h" #include "../SHEditorWindowManager.h"
#include "../AssetBrowser/SHAssetBrowser.h" #include "../AssetBrowser/SHAssetBrowser.h"
#include "Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.h" #include "Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.h"
@ -263,6 +265,10 @@ namespace SHADE
if(rbType == SHRigidBodyComponent::Type::DYNAMIC) //Dynamic only fields if(rbType == SHRigidBodyComponent::Type::DYNAMIC) //Dynamic only fields
{ {
SHEditorWidgets::CheckBox("Use Gravity", [component]{return component->IsGravityEnabled();}, [component](bool const& value){component->SetGravityEnabled(value);}, "Gravity"); SHEditorWidgets::CheckBox("Use Gravity", [component]{return component->IsGravityEnabled();}, [component](bool const& value){component->SetGravityEnabled(value);}, "Gravity");
if (component->IsGravityEnabled())
SHEditorWidgets::DragFloat("Gravity Scale", [component] {return component->GetGravityScale(); }, [component](float const& value) {component->SetGravityScale(value); }, "Gravity Scale");
//SHEditorWidgets::DragFloat("Mass", [component] {return component->GetMass(); }, [component](float const& value) {component->SetMass(value); }, "Mass"); //SHEditorWidgets::DragFloat("Mass", [component] {return component->GetMass(); }, [component](float const& value) {component->SetMass(value); }, "Mass");
} }
if (rbType == SHRigidBodyComponent::Type::DYNAMIC || rbType == SHRigidBodyComponent::Type::KINEMATIC) //Dynamic or Kinematic only fields if (rbType == SHRigidBodyComponent::Type::DYNAMIC || rbType == SHRigidBodyComponent::Type::KINEMATIC) //Dynamic or Kinematic only fields
@ -371,12 +377,26 @@ namespace SHADE
( (
"Radius", "Radius",
[sphereShape] { return sphereShape->GetRelativeRadius(); }, [sphereShape] { return sphereShape->GetRelativeRadius(); },
[sphereShape](float const& value) { sphereShape->SetRelativeRadius(value); }); [sphereShape](float const& value) { sphereShape->SetRelativeRadius(value); }
);
}
else if (collisionShape->GetType() == SHCollisionShape::Type::CAPSULE)
{
SHEditorWidgets::BeginPanel(std::format("{} Capsule #{}", ICON_MD_CIRCLE, i).data(), { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y });
auto* capsuleShape = dynamic_cast<SHCapsule*>(collisionShape);
SHEditorWidgets::DragFloat
(
"Radius",
[capsuleShape] { return capsuleShape->GetRelativeRadius(); },
[capsuleShape](float const& value) { capsuleShape->SetRelativeRadius(value); }
);
SHEditorWidgets::DragFloat
(
"Height",
[capsuleShape] { return capsuleShape->GetRelativeHeight(); },
[capsuleShape](float const& value) { capsuleShape->SetRelativeHeight(value); }
);
} }
//else if (collisionShape->GetType() == SHCollisionShape::Type::CAPSULE)
//{
//}
{ {
SHEditorWidgets::CheckBox("Is Trigger", [collisionShape] { return collisionShape->IsTrigger(); }, [collisionShape](bool value) { collisionShape->SetIsTrigger(value); }); SHEditorWidgets::CheckBox("Is Trigger", [collisionShape] { return collisionShape->IsTrigger(); }, [collisionShape](bool value) { collisionShape->SetIsTrigger(value); });
@ -419,25 +439,20 @@ namespace SHADE
if (ImGui::BeginMenu("Add Collider")) if (ImGui::BeginMenu("Add Collider"))
{ {
int newColl = -1; int newCollider = -1;
if (ImGui::Selectable("Box Collider")) if (ImGui::Selectable("Box Collider"))
{ {
newColl = component->AddBoxCollisionShape(SHVec3::One); newCollider = component->AddBoxCollisionShape(SHVec3::One);
} }
if (ImGui::Selectable("Sphere Collider")) if (ImGui::Selectable("Sphere Collider"))
{ {
newColl = component->AddSphereCollisionShape(1.0f); newCollider = component->AddSphereCollisionShape(1.0f);
}
if (ImGui::Selectable("Capsule Collider"))
{
newCollider = component->AddCapsuleCollisionShape(1.0f, 2.0f);
} }
//No idea why this doesn't work
//if (newColl > 0)
//{
// auto newCollisionShape = component->GetCollisionShape(newColl);
// auto prevCollisionShapeInSeq = component->GetCollisionShape(newColl - 1);
// newCollisionShape.SetCollisionTag(SHCollisionTagMatrix::GetTag(prevCollisionShapeInSeq.GetCollisionTag().GetName()));
//}
ImGui::EndMenu(); ImGui::EndMenu();
} }

View File

@ -25,6 +25,7 @@
#include "Serialization/SHSerialization.h" #include "Serialization/SHSerialization.h"
#include "Serialization/Configurations/SHConfigurationManager.h" #include "Serialization/Configurations/SHConfigurationManager.h"
#include "Editor/EditorWindow/SHEditorWindowManager.h" #include "Editor/EditorWindow/SHEditorWindowManager.h"
#include "Physics/System/SHPhysicsSystem.h"
#include "Physics/System/SHPhysicsDebugDrawSystem.h" #include "Physics/System/SHPhysicsDebugDrawSystem.h"
#include "Camera/SHCameraSystem.h" #include "Camera/SHCameraSystem.h"
#include "Tools/Utilities/SHClipboardUtilities.h" #include "Tools/Utilities/SHClipboardUtilities.h"
@ -359,21 +360,63 @@ namespace SHADE
{ {
if (ImGui::BeginMenu("Physics Settings")) if (ImGui::BeginMenu("Physics Settings"))
{ {
if (auto* physicsSystem = SHSystemManager::GetSystem<SHPhysicsSystem>())
{
SHEditorWidgets::DragVec3
(
"Gravity", { "X", "Y", "Z" },
[physicsSystem] {return physicsSystem->GetGravity(); },
[physicsSystem](SHVec3 const& value) { physicsSystem->SetGravity(value); }
, false, "Global Gravity", 0.1f, "%.3f", 0.0f, 0.0f
);
SHEditorWidgets::SliderScalar<uint16_t>
(
"Velocity Iterations", ImGuiDataType_U16, (uint16_t)1, (uint16_t)32,
[physicsSystem] { return physicsSystem->GetNumVelocityIterations(); },
[physicsSystem](uint16_t value) { physicsSystem->SetNumVelocityIterations(value); },
"Number of times velocity is solved per collision. Higher values increase precision at the cost of performance.",
"%zu"
);
SHEditorWidgets::SliderScalar<uint16_t>
(
"Position Iterations", ImGuiDataType_U16, (uint16_t)1, (uint16_t)32,
[physicsSystem] { return physicsSystem->GetNumPositionIterations(); },
[physicsSystem](uint16_t value) { physicsSystem->SetNumPositionIterations(value); },
"Number of times position is solved per collision. Higher values increase precision at the cost of performance.",
"%zu"
);
SHEditorWidgets::CheckBox
(
"Sleeping Enabled",
[physicsSystem] { return physicsSystem->IsSleepingEnabled(); },
[physicsSystem](bool value) { physicsSystem->EnableSleeping(value); },
"If bodies are allowed to sleep. Sleeping increases performance of the simulation and should be left enabled."
);
}
if (auto* physicsDebugDraw = SHSystemManager::GetSystem<SHPhysicsDebugDrawSystem>()) if (auto* physicsDebugDraw = SHSystemManager::GetSystem<SHPhysicsDebugDrawSystem>())
{ {
bool drawColliders = physicsDebugDraw->GetFlagState(SHPhysicsDebugDrawSystem::DebugDrawFlags::COLLIDERS); if(ImGui::CollapsingHeader("Debug Draw", ImGuiTreeNodeFlags_DefaultOpen))
if (ImGui::Checkbox("Draw Colliders", &drawColliders)) {
physicsDebugDraw->SetFlagState(SHPhysicsDebugDrawSystem::DebugDrawFlags::COLLIDERS, drawColliders); bool drawColliders = physicsDebugDraw->GetFlagState(SHPhysicsDebugDrawSystem::DebugDrawFlags::COLLIDERS);
if (ImGui::Checkbox("Draw Colliders", &drawColliders))
physicsDebugDraw->SetFlagState(SHPhysicsDebugDrawSystem::DebugDrawFlags::COLLIDERS, drawColliders);
bool drawContactPoints = physicsDebugDraw->GetFlagState(SHPhysicsDebugDrawSystem::DebugDrawFlags::CONTACTS); bool drawContactPoints = physicsDebugDraw->GetFlagState(SHPhysicsDebugDrawSystem::DebugDrawFlags::CONTACTS);
if (ImGui::Checkbox("Draw Contact Points", &drawContactPoints)) if (ImGui::Checkbox("Draw Contact Points", &drawContactPoints))
physicsDebugDraw->SetFlagState(SHPhysicsDebugDrawSystem::DebugDrawFlags::CONTACTS, drawContactPoints); physicsDebugDraw->SetFlagState(SHPhysicsDebugDrawSystem::DebugDrawFlags::CONTACTS, drawContactPoints);
bool drawRays = physicsDebugDraw->GetFlagState(SHPhysicsDebugDrawSystem::DebugDrawFlags::RAYCASTS); bool drawRays = physicsDebugDraw->GetFlagState(SHPhysicsDebugDrawSystem::DebugDrawFlags::RAYCASTS);
if (ImGui::Checkbox("Draw Rays", &drawRays)) if (ImGui::Checkbox("Draw Rays", &drawRays))
physicsDebugDraw->SetFlagState(SHPhysicsDebugDrawSystem::DebugDrawFlags::RAYCASTS, drawRays); physicsDebugDraw->SetFlagState(SHPhysicsDebugDrawSystem::DebugDrawFlags::RAYCASTS, drawRays);
}
} }
ImGui::EndMenu(); ImGui::EndMenu();
} }
} }

View File

@ -375,15 +375,15 @@ namespace SHADE
const SHVec3 LOCAL_FORWARD = SHVec3::Rotate(SHVec3::Forward, rotation); const SHVec3 LOCAL_FORWARD = SHVec3::Rotate(SHVec3::Forward, rotation);
// Rotate the circle // Rotate the circle
SHQuaternion circleOrientation = SHQuaternion::FromEuler(SHVec3(SHMath::DegreesToRadians(90.0), 0.0f, 0.0f)) * rotation; SHQuaternion circleOrientation = SHQuaternion::FromEuler(SHVec3(SHMath::DegreesToRadians(90.0f), 0.0f, 0.0f)) * rotation;
// Compute top and bottom of the cylinder // Compute top and bottom of the cylinder
const SHVec3 HALF_UP = LOCAL_UP * (height * 0.5f - radius); const SHVec3 HALF_UP = LOCAL_UP * (height * 0.5f);
const SHVec3 TOP_POS = position + HALF_UP; const SHVec3 TOP_POS = position + HALF_UP;
const SHVec3 BOT_POS = position - HALF_UP; const SHVec3 BOT_POS = position - HALF_UP;
// Render circles // Render circles
const SHVec3 CIRCLE_SCALE = SHVec3(radius * 2.0f, radius * 2.0, radius * 2.0); const SHVec3 CIRCLE_SCALE = SHVec3(radius * 2.0f, radius * 2.0f, radius * 2.0f);
drawCircle(meshBatch, SHMatrix::Transform(TOP_POS, circleOrientation, CIRCLE_SCALE), color); drawCircle(meshBatch, SHMatrix::Transform(TOP_POS, circleOrientation, CIRCLE_SCALE), color);
drawCircle(meshBatch, SHMatrix::Transform(BOT_POS, circleOrientation, CIRCLE_SCALE), color); drawCircle(meshBatch, SHMatrix::Transform(BOT_POS, circleOrientation, CIRCLE_SCALE), color);
@ -394,7 +394,7 @@ namespace SHADE
drawLine(lineBatch, TOP_POS - LOCAL_FORWARD * radius, BOT_POS - LOCAL_FORWARD * radius, color); drawLine(lineBatch, TOP_POS - LOCAL_FORWARD * radius, BOT_POS - LOCAL_FORWARD * radius, color);
// Render caps // Render caps
const SHVec3 RADIUS_SCALE = SHVec3(radius * 2.0, radius * 2.0f, radius * 2.0); const SHVec3 RADIUS_SCALE = SHVec3(radius * 2.0f, radius * 2.0f, radius * 2.0f);
const SHMatrix TOP_CAP_MAT = SHMatrix::Transform(TOP_POS, rotation, RADIUS_SCALE); const SHMatrix TOP_CAP_MAT = SHMatrix::Transform(TOP_POS, rotation, RADIUS_SCALE);
drawMesh drawMesh
( (
@ -404,7 +404,7 @@ namespace SHADE
const SHMatrix BOT_CAP_MAT = SHMatrix::Transform const SHMatrix BOT_CAP_MAT = SHMatrix::Transform
( (
BOT_POS, BOT_POS,
SHQuaternion::FromEuler(SHVec3(SHMath::DegreesToRadians(180.0), 0.0f, 0.0f)) * rotation, SHQuaternion::FromEuler(SHVec3(SHMath::DegreesToRadians(180.0f), 0.0f, 0.0f)) * rotation,
RADIUS_SCALE RADIUS_SCALE
); );
drawMesh drawMesh

View File

@ -0,0 +1,215 @@
/****************************************************************************************
* \file SHAABB.cpp
* \author Diren D Bharwani, diren.dbharwani, 390002520
* \brief Implementation for a 3-Dimensional Axis Aligned Bounding Box
*
* \copyright Copyright (C) 2022 DigiPen Institute of Technology. Reproduction or
* disclosure of this file or its contents without the prior written consent
* of DigiPen Institute of Technology is prohibited.
****************************************************************************************/
#include <SHpch.h>
// Primary Header
#include "SHAABB.h"
// Project Headers
#include "Math/SHMathHelpers.h"
#include "Math/SHRay.h"
using namespace DirectX;
namespace SHADE
{
/*-----------------------------------------------------------------------------------*/
/* Constructors & Destructor Definitions */
/*-----------------------------------------------------------------------------------*/
SHAABB::SHAABB() noexcept
{
Center = SHVec3::Zero;
Extents = SHVec3::One * 0.5f;
}
SHAABB::SHAABB(const SHVec3& c, const SHVec3& hE) noexcept
{
Center = c;
Extents = hE;
}
SHAABB::SHAABB(const SHAABB& rhs) noexcept
{
if (this == &rhs)
return;
Center = rhs.Center;
Extents = rhs.Extents;
}
SHAABB::SHAABB(SHAABB&& rhs) noexcept
{
Center = rhs.Center;
Extents = rhs.Extents;
}
/*-----------------------------------------------------------------------------------*/
/* Operator Overload Definitions */
/*-----------------------------------------------------------------------------------*/
SHAABB& SHAABB::operator=(const SHAABB& rhs) noexcept
{
Center = rhs.Center;
Extents = rhs.Extents;
return *this;
}
SHAABB& SHAABB::operator=(SHAABB&& rhs) noexcept
{
Center = rhs.Center;
Extents = rhs.Extents;
return *this;
}
/*-----------------------------------------------------------------------------------*/
/* Getter Function Definitions */
/*-----------------------------------------------------------------------------------*/
SHVec3 SHAABB::GetCenter() const noexcept
{
return Center;
}
SHVec3 SHAABB::GetExtents() const noexcept
{
return Extents;
}
SHVec3 SHAABB::GetMin() const noexcept
{
return SHVec3{ Center.x - Extents.x, Center.y - Extents.y, Center.z - Extents.z };
}
SHVec3 SHAABB::GetMax() const noexcept
{
return SHVec3{ Center.x + Extents.x, Center.y + Extents.y, Center.z + Extents.z };
}
/*-----------------------------------------------------------------------------------*/
/* Setter Function Definitions */
/*-----------------------------------------------------------------------------------*/
void SHAABB::SetCenter(const SHVec3& newCenter) noexcept
{
Center = newCenter;
}
void SHAABB::SetExtents(const SHVec3& newExtents) noexcept
{
Extents = newExtents;
}
void SHAABB::SetMin(const SHVec3& min) noexcept
{
const SHVec3 MAX = GetMax();
Center = SHVec3::Lerp(min, MAX, 0.5f);
Extents = SHVec3::Abs((MAX - min) * 0.5f);
}
void SHAABB::SetMax(const SHVec3& max) noexcept
{
const SHVec3 MIN = GetMin();
Center = SHVec3::Lerp(MIN, max, 0.5f);
Extents = SHVec3::Abs((max - MIN) * 0.5f);
}
void SHAABB::SetMinMax(const SHVec3& min, const SHVec3& max) noexcept
{
Center = SHVec3::Lerp(min, max, 0.5f);
Extents = SHVec3::Abs((max - min) * 0.5f);
}
std::vector<SHVec3> SHAABB::GetVertices() const noexcept
{
std::vector<SHVec3> vertices{ 8 };
GetCorners(vertices.data());
return vertices;
}
/*-----------------------------------------------------------------------------------*/
/* Public Function Member Definitions */
/*-----------------------------------------------------------------------------------*/
bool SHAABB::TestPoint(const SHVec3& point) const noexcept
{
return BoundingBox::Contains(point);
}
SHRaycastResult SHAABB::Raycast(const SHRay& ray) const noexcept
{
SHRaycastResult result;
result.hit = Intersects(ray.position, ray.direction, result.distance);
if (result.hit)
{
result.position = ray.position + ray.direction * result.distance;
result.angle = SHVec3::Angle(ray.position, result.position);
}
return result;
}
bool SHAABB::Contains(const SHAABB& rhs) const noexcept
{
return BoundingBox::Contains(rhs) == CONTAINS;
}
float SHAABB::Volume() const noexcept
{
return 8.0f * (Extents.x * Extents.y * Extents.z);
}
float SHAABB::SurfaceArea() const noexcept
{
return 8.0f * ((Extents.x * Extents.y)
+ (Extents.x * Extents.z)
+ (Extents.y * Extents.z));
}
/*-----------------------------------------------------------------------------------*/
/* Static Function Member Definitions */
/*-----------------------------------------------------------------------------------*/
SHAABB SHAABB::Combine(const SHAABB& lhs, const SHAABB& rhs) noexcept
{
SHAABB result;
CreateMerged(result, lhs, rhs);
return result;
}
bool SHAABB::Intersect(const SHAABB& lhs, const SHAABB& rhs) noexcept
{
return lhs.Intersects(rhs);
}
SHAABB SHAABB::BuildFromBoxes(const SHAABB* boxes, size_t numBoxes) noexcept
{
SHAABB result;
for (size_t i = 1; i < numBoxes; ++i)
CreateMerged(result, boxes[i - 1], boxes[i]);
return result;
}
SHAABB SHAABB::BuildFromVertices(const SHVec3* vertices, size_t numVertices, size_t stride) noexcept
{
SHAABB result;
CreateFromPoints(result, numVertices, vertices, stride);
return result;
}
} // namespace SHADE

View File

@ -0,0 +1,172 @@
/****************************************************************************************
* \file SHAABB.h
* \author Diren D Bharwani, diren.dbharwani, 390002520
* \brief Interface for a 3-Dimensional Axis Aligned Bounding Box
*
* \copyright Copyright (C) 2022 DigiPen Institute of Technology. Reproduction or
* disclosure of this file or its contents without the prior written consent
* of DigiPen Institute of Technology is prohibited.
****************************************************************************************/
#pragma once
#include <DirectXCollision.h>
// Project Headers
#include "Math/SHRay.h"
namespace SHADE
{
/*-----------------------------------------------------------------------------------*/
/* Type Definitions */
/*-----------------------------------------------------------------------------------*/
/**
* @brief
* Encapsulates a 3D Axis-Aligned Bounding Box.
*/
class SH_API SHAABB : private DirectX::BoundingBox
{
public:
/*---------------------------------------------------------------------------------*/
/* Static Data Members */
/*---------------------------------------------------------------------------------*/
static constexpr size_t NUM_VERTICES = 8;
/*---------------------------------------------------------------------------------*/
/* Constructors & Destructor */
/*---------------------------------------------------------------------------------*/
~SHAABB () noexcept = default;
SHAABB () noexcept;
SHAABB (const SHVec3& center, const SHVec3& halfExtents) noexcept;
SHAABB (const SHAABB& rhs) noexcept;
SHAABB (SHAABB&& rhs) noexcept;
/*---------------------------------------------------------------------------------*/
/* Operator Overloads */
/*---------------------------------------------------------------------------------*/
SHAABB& operator= (const SHAABB& rhs) noexcept;
SHAABB& operator= (SHAABB&& rhs) noexcept;
/*---------------------------------------------------------------------------------*/
/* Getter Functions */
/*---------------------------------------------------------------------------------*/
[[nodiscard]] SHVec3 GetCenter () const noexcept;
[[nodiscard]] SHVec3 GetExtents () const noexcept;
[[nodiscard]] SHVec3 GetMin () const noexcept;
[[nodiscard]] SHVec3 GetMax () const noexcept;
[[nodiscard]] std::vector<SHVec3> GetVertices () const noexcept;
/*---------------------------------------------------------------------------------*/
/* Setter Functions */
/*---------------------------------------------------------------------------------*/
void SetCenter (const SHVec3& newCenter) noexcept;
void SetExtents (const SHVec3& newExtents) noexcept;
void SetMin (const SHVec3& min) noexcept;
void SetMax (const SHVec3& max) noexcept;
void SetMinMax (const SHVec3& min, const SHVec3& max) noexcept;
/*---------------------------------------------------------------------------------*/
/* Member Functions */
/*---------------------------------------------------------------------------------*/
/**
* @brief
* Checks if a point is inside the aabb.
* @param point
* The point to check.
* @return
* True if the point is inside the aabb.
*/
[[nodiscard]] bool TestPoint (const SHVec3& point) const noexcept;
/**
* @brief
* Casts a ray against the aabb.
* @param ray
* The ray to cast.
* @return
* The result of the raycast. <br/>
* See the corresponding header for the contents of the raycast result object.
*/
[[nodiscard]] SHRaycastResult Raycast (const SHRay& ray) const noexcept;
/**
* @brief
* Checks if an entire other aabb is contained by this aabb.
* @param rhs
* The aabb to check.
* @return
* True if the other sphere is completely contained by this aabb.
*/
[[nodiscard]] bool Contains (const SHAABB& rhs) const noexcept;
/**
* @brief
* Calculates the volume of the aabb.
*/
[[nodiscard]] float Volume () const noexcept;
/**
* @brief
* Calculates the surface area of the aabb.
*/
[[nodiscard]] float SurfaceArea () const noexcept;
/*---------------------------------------------------------------------------------*/
/* Static Member Functions */
/*---------------------------------------------------------------------------------*/
/**
* @brief
* Combines two aabbs to form a larger aabb.
* If one aabb is completely contained by the other, the result is the larger aabb.
* @return
* The combined aabb.
*/
[[nodiscard]] static SHAABB Combine (const SHAABB& lhs, const SHAABB& rhs) noexcept;
/**
* @brief
* Checks if two aabbs are intersecting.
* @return
* True if they are intersecting.
*/
[[nodiscard]] static bool Intersect (const SHAABB& lhs, const SHAABB& rhs) noexcept;
/**
* @brief
* Builds a single aabb from multiple aabbs.
* @param spheres
* The set of aabbs to build from.
* @param numSpheres
* The number of aabbs in the set to build from.
* @return
* An aabb that contains all the spheres in the set.
*/
[[nodiscard]] static SHAABB BuildFromBoxes (const SHAABB* boxes, size_t numBoxes) noexcept;
/**
* @brief
* Builds a aabb from a set of vertices.
* @param vertices
* The vertices to build a aabb from.
* @param numVertices
* The number of vertices in the set to build from.
* @param stride
* The stride between each vertex, in the instance there is data in between each
* vertex that does not define the geometry of the object.
* @return
* An aabb that contains all the vertices in the set.
*/
[[nodiscard]] static SHAABB BuildFromVertices (const SHVec3* vertices, size_t numVertices, size_t stride = 0) noexcept;
};
} // namespace SHADE

View File

@ -1,5 +1,5 @@
/**************************************************************************************** /****************************************************************************************
* \file SHBoxCollisionShape.cpp * \file SHBox.cpp
* \author Diren D Bharwani, diren.dbharwani, 390002520 * \author Diren D Bharwani, diren.dbharwani, 390002520
* \brief Implementation for a Box Collision Shape. * \brief Implementation for a Box Collision Shape.
* *
@ -34,10 +34,6 @@ namespace SHADE
dynamic_cast<rp3d::BoxShape*>(rp3dCollider->getCollisionShape())->setHalfExtents(SHVec3::One * 0.5f); dynamic_cast<rp3d::BoxShape*>(rp3dCollider->getCollisionShape())->setHalfExtents(SHVec3::One * 0.5f);
} }
/*-----------------------------------------------------------------------------------*/
/* Operator Overload Definitions */
/*-----------------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
/* Getter Function Definitions */ /* Getter Function Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/

View File

@ -40,10 +40,6 @@ namespace SHADE
SHBox () noexcept; SHBox () noexcept;
~SHBox () override = default; ~SHBox () override = default;
/*---------------------------------------------------------------------------------*/
/* Operator Overloads */
/*---------------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Getter Functions */ /* Getter Functions */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/

View File

@ -0,0 +1,166 @@
/****************************************************************************************
* \file SHCapsule.cpp
* \author Diren D Bharwani, diren.dbharwani, 390002520
* \brief Implementation for a Capsule Collision Shape.
*
* \copyright Copyright (C) 2022 DigiPen Institute of Technology. Reproduction or
* disclosure of this file or its contents without the prior written consent
* of DigiPen Institute of Technology is prohibited.
****************************************************************************************/
#include <SHpch.h>
#include <reactphysics3d/reactphysics3d.h>
// Primary Header
#include "SHCapsule.h"
// Project Headers
#include "Math/SHMathHelpers.h"
#include "Math/SHMatrix.h"
#include "Physics/Interface/SHColliderComponent.h"
namespace SHADE
{
/*-----------------------------------------------------------------------------------*/
/* Constructors & Destructor Definitions */
/*-----------------------------------------------------------------------------------*/
SHCapsule::SHCapsule() noexcept
: SHCollisionShape ( Type::CAPSULE)
, relativeRadius { 1.0f }
, relativeHeight { 2.0f }
, scale { SHVec3::One }
{
if (rp3dCollider)
{
auto* rp3dCapsule = dynamic_cast<rp3d::CapsuleShape*>(rp3dCollider->getCollisionShape());
rp3dCapsule->setRadius(0.5f);
rp3dCapsule->setHeight(2.0f);
}
}
/*-----------------------------------------------------------------------------------*/
/* Getter Function Definitions */
/*-----------------------------------------------------------------------------------*/
float SHCapsule::GetWorldRadius() const noexcept
{
if (rp3dCollider)
return dynamic_cast<rp3d::CapsuleShape*>(rp3dCollider->getCollisionShape())->getRadius();
const float MAX_SCALE = SHMath::Max(scale.x, scale.z);
return relativeRadius * MAX_SCALE * 0.5f;
}
float SHCapsule::GetRelativeRadius() const noexcept
{
return relativeRadius;
}
float SHCapsule::GetWorldHeight() const noexcept
{
if (rp3dCollider)
return dynamic_cast<rp3d::CapsuleShape*>(rp3dCollider->getCollisionShape())->getHeight();
return relativeHeight * scale.y;
}
float SHCapsule::GetRelativeHeight() const noexcept
{
return relativeHeight;
}
SHVec3 SHCapsule::GetWorldCentroid() const noexcept
{
const SHQuaternion ROTATION = collider->GetTransform().orientation * SHQuaternion::FromEuler(rotationOffset);
const SHMatrix TRS = SHMatrix::Rotate(ROTATION) * SHMatrix::Translate(collider->GetTransform().position);
return SHVec3::Transform(positionOffset, TRS);
}
/*-----------------------------------------------------------------------------------*/
/* Setter Function Definitions */
/*-----------------------------------------------------------------------------------*/
void SHCapsule::SetWorldRadius(float newWorldRadius) noexcept
{
if (rp3dCollider)
dynamic_cast<rp3d::CapsuleShape*>(rp3dCollider->getCollisionShape())->setRadius(newWorldRadius);
// Recompute Relative radius
const float MAX_SCALE = SHMath::Max(scale.x, scale.z);
relativeRadius = 2.0f * newWorldRadius / MAX_SCALE;
}
void SHCapsule::SetRelativeRadius(float newRelativeRadius) noexcept
{
relativeRadius = newRelativeRadius;
// Recompute world radius
if (rp3dCollider)
{
auto* rp3dCapsule = dynamic_cast<rp3d::CapsuleShape*>(rp3dCollider->getCollisionShape());
const float MAX_SCALE = SHMath::Max(scale.x, scale.z);
rp3dCapsule->setRadius(relativeRadius * MAX_SCALE * 0.5f);
}
}
void SHCapsule::SetWorldHeight(float newWorldHeight) noexcept
{
if (rp3dCollider)
dynamic_cast<rp3d::CapsuleShape*>(rp3dCollider->getCollisionShape())->setHeight(newWorldHeight);
relativeHeight = newWorldHeight / scale.y;
}
void SHCapsule::SetRelativeHeight(float newRelativeHeight) noexcept
{
relativeHeight = newRelativeHeight;
if (rp3dCollider)
dynamic_cast<rp3d::CapsuleShape*>(rp3dCollider->getCollisionShape())->setHeight(relativeHeight * scale.y);
}
void SHCapsule::SetScale(const SHVec3& newScale) noexcept
{
scale = SHVec3::Abs(newScale);
// Recompute world radius & Height
if (rp3dCollider)
{
// Get max scale component
const float MAX_SCALE = SHMath::Max(scale.x, scale.z);
auto* rp3dCapsule = dynamic_cast<rp3d::CapsuleShape*>(rp3dCollider->getCollisionShape());
rp3dCapsule->setRadius(relativeRadius * MAX_SCALE * 0.5f);
rp3dCapsule->setHeight(relativeHeight * scale.y);
}
}
/*-----------------------------------------------------------------------------------*/
/* Public Member Function Definitions */
/*-----------------------------------------------------------------------------------*/
void SHCapsule::Update() noexcept
{
const SHTransform& PARENT_TRANSFORM = collider->GetTransform();
SetScale(PARENT_TRANSFORM.scale);
SHCollisionShape::Update();
}
SHMatrix SHCapsule::GetTRS() const noexcept
{
// The scale of a Capsule would probably be the radius set in the x and z axis, with the height set in the y axis.
// Arbitrary for debug drawing as we specify the position, rotation, height and radius instead.
const SHQuaternion ROTATION = collider->GetTransform().orientation * SHQuaternion::FromEuler(rotationOffset);
const SHVec3 SCALE = SHVec3{ GetWorldRadius(), GetWorldHeight(), GetWorldRadius() };
const SHMatrix TRS = SHMatrix::Rotate(ROTATION) * SHMatrix::Translate(collider->GetTransform().position);
const SHVec3 POSITION = SHVec3::Transform(positionOffset, TRS);
return SHMatrix::Transform(POSITION, ROTATION, SCALE);
}
} // namespace SHADE

View File

@ -0,0 +1,82 @@
/****************************************************************************************
* \file SHCapsule.h
* \author Diren D Bharwani, diren.dbharwani, 390002520
* \brief Interface for a Capsule Collision Shape.
*
* \copyright Copyright (C) 2022 DigiPen Institute of Technology. Reproduction or
* disclosure of this file or its contents without the prior written consent
* of DigiPen Institute of Technology is prohibited.
****************************************************************************************/
#pragma once
// Project Headers
#include "SHCollisionShape.h"
namespace SHADE
{
/*-----------------------------------------------------------------------------------*/
/* Type Definitions */
/*-----------------------------------------------------------------------------------*/
/**
* @brief
* Encapsulate a Capsule Shape used for Physics Simulations.
*/
class SH_API SHCapsule final : public SHCollisionShape
{
private:
/*---------------------------------------------------------------------------------*/
/* Friends */
/*---------------------------------------------------------------------------------*/
friend class SHColliderComponent;
public:
/*---------------------------------------------------------------------------------*/
/* Constructors & Destructor */
/*---------------------------------------------------------------------------------*/
SHCapsule () noexcept;
~SHCapsule () override = default;
/*---------------------------------------------------------------------------------*/
/* Getter Functions */
/*---------------------------------------------------------------------------------*/
[[nodiscard]] float GetWorldRadius () const noexcept;
[[nodiscard]] float GetRelativeRadius () const noexcept;
[[nodiscard]] float GetWorldHeight () const noexcept;
[[nodiscard]] float GetRelativeHeight () const noexcept;
[[nodiscard]] SHVec3 GetWorldCentroid () const noexcept override;
/*---------------------------------------------------------------------------------*/
/* Setter Functions */
/*---------------------------------------------------------------------------------*/
void SetWorldRadius (float newWorldRadius) noexcept;
void SetRelativeRadius (float newRelativeRadius) noexcept;
void SetWorldHeight (float newWorldHeight) noexcept;
void SetRelativeHeight (float newRelativeHeight) noexcept;
void SetScale (const SHVec3& newScale) noexcept;
/*---------------------------------------------------------------------------------*/
/* Function Members */
/*---------------------------------------------------------------------------------*/
void Update () noexcept override;
[[nodiscard]] SHMatrix GetTRS () const noexcept override;
private:
/*---------------------------------------------------------------------------------*/
/* Data Members */
/*---------------------------------------------------------------------------------*/
float relativeRadius;
float relativeHeight;
SHVec3 scale;
};
} // namespace SHADE

View File

@ -237,9 +237,9 @@ RTTR_REGISTRATION
registration::enumeration<SHCollisionShape::Type>("Collider Type") registration::enumeration<SHCollisionShape::Type>("Collider Type")
( (
value("Sphere", SHCollisionShape::Type::SPHERE),
value("Box", SHCollisionShape::Type::BOX), value("Box", SHCollisionShape::Type::BOX),
value("Sphere", SHCollisionShape::Type::SPHERE) value("Capsule", SHCollisionShape::Type::CAPSULE)
// TODO(Diren): Add More Shapes
); );
registration::class_<SHCollisionShape>("Collider") registration::class_<SHCollisionShape>("Collider")

View File

@ -53,6 +53,7 @@ namespace SHADE
{ {
SPHERE SPHERE
, BOX , BOX
, CAPSULE
, COUNT , COUNT
, INVALID = -1 , INVALID = -1

View File

@ -18,6 +18,7 @@
#include "Physics/Collision/CollisionTags/SHCollisionTagMatrix.h" #include "Physics/Collision/CollisionTags/SHCollisionTagMatrix.h"
#include "Physics/Collision/Shapes/SHSphere.h" #include "Physics/Collision/Shapes/SHSphere.h"
#include "Physics/Collision/Shapes/SHBox.h" #include "Physics/Collision/Shapes/SHBox.h"
#include "Physics/Collision/Shapes/SHCapsule.h"
#include "Physics/Interface/SHColliderComponent.h" #include "Physics/Interface/SHColliderComponent.h"
#include "Physics/Interface/SHRigidBodyComponent.h" #include "Physics/Interface/SHRigidBodyComponent.h"
#include "Tools/Utilities/SHUtilities.h" #include "Tools/Utilities/SHUtilities.h"
@ -228,7 +229,7 @@ namespace SHADE
{ {
SHColliderDef::ShapeDef shapeDef SHColliderDef::ShapeDef shapeDef
{ {
.type = shape->GetType() .type = shape->GetType()
}; };
colliderDef.shapes.emplace_back(shapeDef); colliderDef.shapes.emplace_back(shapeDef);
@ -297,6 +298,7 @@ namespace SHADE
rigidBodyComponent->SetInterpolate (rigidBodyComponent->IsInterpolating()); rigidBodyComponent->SetInterpolate (rigidBodyComponent->IsInterpolating());
rigidBodyComponent->SetDrag (rigidBodyComponent->GetDrag()); rigidBodyComponent->SetDrag (rigidBodyComponent->GetDrag());
rigidBodyComponent->SetAngularDrag (rigidBodyComponent->GetAngularDrag()); rigidBodyComponent->SetAngularDrag (rigidBodyComponent->GetAngularDrag());
rigidBodyComponent->SetGravityScale (rigidBodyComponent->GetGravityScale());
rigidBodyQueue.pop(); rigidBodyQueue.pop();
} }
@ -367,6 +369,22 @@ namespace SHADE
break; break;
} }
case SHCollisionShape::Type::CAPSULE:
{
auto* capsuleShape = dynamic_cast<SHCapsule*>(collisionShape);
const float MAX_SCALE = SHMath::Max({ colliderComponent->transform.scale.x, colliderComponent->transform.scale.y, colliderComponent->transform.scale.z });
const float WORLD_RADIUS = capsuleShape->GetRelativeRadius() * MAX_SCALE * 0.5f;
const float WORLD_HEIGHT = capsuleShape->GetRelativeHeight() * colliderComponent->transform.scale.y;
rp3d::CapsuleShape* rp3dCapsule = factory->createCapsuleShape(WORLD_RADIUS, WORLD_HEIGHT);
const rp3d::Transform OFFSETS{ capsuleShape->GetPositionOffset(), SHQuaternion::FromEuler(capsuleShape->GetRotationOffset()) };
capsuleShape->rp3dCollider = physicsObject->body->addCollider(rp3dCapsule, OFFSETS);
capsuleShape->rp3dCollider->setIsTrigger(capsuleShape->IsTrigger());
break;
}
default: break; default: break;
} }

View File

@ -20,6 +20,7 @@
#include "Physics/SHPhysicsEvents.h" #include "Physics/SHPhysicsEvents.h"
#include "Physics/Collision/Shapes/SHSphere.h" #include "Physics/Collision/Shapes/SHSphere.h"
#include "Physics/Collision/Shapes/SHBox.h" #include "Physics/Collision/Shapes/SHBox.h"
#include "Physics/Collision/Shapes/SHCapsule.h"
namespace SHADE namespace SHADE
{ {
@ -232,6 +233,49 @@ namespace SHADE
return static_cast<int>(NEW_INDEX); return static_cast<int>(NEW_INDEX);
} }
int SHColliderComponent::AddCapsuleCollisionShape(float relativeRadius, float relativeHeight, const SHVec3& posOffset, const SHVec3& rotOffset)
{
const uint32_t NEW_INDEX = static_cast<uint32_t>(shapes.size());
// Create collision shape
shapes.emplace_back(new SHCapsule{});
auto* newCapsule = dynamic_cast<SHCapsule*>(shapes.back());
newCapsule->collider = this;
newCapsule->positionOffset = posOffset;
newCapsule->rotationOffset = rotOffset;
newCapsule->relativeRadius = relativeRadius;
newCapsule->relativeHeight = relativeHeight;
newCapsule->scale = SHVec3::Abs(transform.scale);
// Broadcast Event for adding a shape
const SHPhysicsColliderAddedEvent EVENT_DATA
{
.entityID = GetEID()
, .colliderType = SHCollisionShape::Type::CAPSULE
, .colliderIndex = static_cast<int>(NEW_INDEX)
};
SHEventManager::BroadcastEvent<SHPhysicsColliderAddedEvent>(EVENT_DATA, SH_PHYSICS_COLLIDER_ADDED_EVENT);
if (factory)
{
const float MAX_SCALE = SHMath::Max(newCapsule->scale.x, newCapsule->scale.z);
const float WORLD_RADIUS = relativeRadius * MAX_SCALE * 0.5f;
const float WORLD_HEIGHT = relativeHeight * newCapsule->scale.y;
rp3d::CapsuleShape* rp3dCapsule = factory->createCapsuleShape(WORLD_RADIUS, WORLD_HEIGHT);
const rp3d::Transform OFFSETS{ posOffset, SHQuaternion::FromEuler(rotOffset) };
newCapsule->rp3dCollider = collisionBody->addCollider(rp3dCapsule, OFFSETS);
dynamic_cast<rp3d::RigidBody*>(collisionBody)->updateMassPropertiesFromColliders();
}
return static_cast<int>(NEW_INDEX);
}
void SHColliderComponent::RemoveCollisionShape(int index) void SHColliderComponent::RemoveCollisionShape(int index)
{ {
const int NUM_SHAPES = static_cast<int>(shapes.size()); const int NUM_SHAPES = static_cast<int>(shapes.size());

View File

@ -142,6 +142,24 @@ namespace SHADE
*/ */
int AddBoxCollisionShape (const SHVec3& relativeExtents, const SHVec3& posOffset = SHVec3::Zero, const SHVec3& rotOffset = SHVec3::Zero); int AddBoxCollisionShape (const SHVec3& relativeExtents, const SHVec3& posOffset = SHVec3::Zero, const SHVec3& rotOffset = SHVec3::Zero);
/**
* @brief
* Adds a capsule collision shape.
* @param relativeRadius
* The relative radius is constructed with respect to the world scale. <br/>
* Radius = max(scale.x, scale.y, scale.z) * 0.5 * relativeRadius
* @param relativeHeight
* The relative height is constructed with respect to the scale in the y-axis <br/>
* Height = relativeHeight * scale.y
* @param posOffset
* The position offset of the box from the center of the collider. Defaults to a Zero Vector.
* @param rotOffset
* The rotation offset of the box from the rotation of the collider. Defaults to a Zero Vector.
* @return
* The index of the newly added shape.
*/
int AddCapsuleCollisionShape (float relativeRadius, float relativeHeight, const SHVec3& posOffset = SHVec3::Zero, const SHVec3& rotOffset = SHVec3::Zero);
/** /**
* @brief * @brief
* Removes a shape from the container. Removal reduces the size of the container. * Removes a shape from the container. Removal reduces the size of the container.

View File

@ -114,6 +114,11 @@ namespace SHADE
return angularDrag; return angularDrag;
} }
float SHRigidBodyComponent::GetGravityScale() const noexcept
{
return gravityScale;
}
SHVec3 SHRigidBodyComponent::GetForce() const noexcept SHVec3 SHRigidBodyComponent::GetForce() const noexcept
{ {
return rigidBody ? SHVec3{ rigidBody->getForce() } : SHVec3::Zero; return rigidBody ? SHVec3{ rigidBody->getForce() } : SHVec3::Zero;
@ -297,6 +302,15 @@ namespace SHADE
rigidBody->setAngularDamping(newAngularDrag); rigidBody->setAngularDamping(newAngularDrag);
} }
void SHRigidBodyComponent::SetGravityScale(float newGravityScale) noexcept
{
gravityScale = newGravityScale;
if (rigidBody)
rigidBody->setGravityScale(newGravityScale);
}
void SHRigidBodyComponent::SetLinearVelocity(const SHVec3& newLinearVelocity) noexcept void SHRigidBodyComponent::SetLinearVelocity(const SHVec3& newLinearVelocity) noexcept
{ {
if (type == Type::STATIC) if (type == Type::STATIC)
@ -408,6 +422,7 @@ RTTR_REGISTRATION
.property("Type" , &SHRigidBodyComponent::GetType , &SHRigidBodyComponent::SetType ) .property("Type" , &SHRigidBodyComponent::GetType , &SHRigidBodyComponent::SetType )
.property("Drag" , &SHRigidBodyComponent::GetDrag , &SHRigidBodyComponent::SetDrag ) .property("Drag" , &SHRigidBodyComponent::GetDrag , &SHRigidBodyComponent::SetDrag )
.property("Angular Drag" , &SHRigidBodyComponent::GetAngularDrag , &SHRigidBodyComponent::SetAngularDrag ) .property("Angular Drag" , &SHRigidBodyComponent::GetAngularDrag , &SHRigidBodyComponent::SetAngularDrag )
.property("Gravity Scale" , &SHRigidBodyComponent::GetGravityScale , &SHRigidBodyComponent::SetGravityScale )
.property("Use Gravity" , &SHRigidBodyComponent::IsGravityEnabled , &SHRigidBodyComponent::SetGravityEnabled ) .property("Use Gravity" , &SHRigidBodyComponent::IsGravityEnabled , &SHRigidBodyComponent::SetGravityEnabled )
.property("Interpolate" , &SHRigidBodyComponent::IsInterpolating , &SHRigidBodyComponent::SetInterpolate ) .property("Interpolate" , &SHRigidBodyComponent::IsInterpolating , &SHRigidBodyComponent::SetInterpolate )
.property("Sleeping Enabled" , &SHRigidBodyComponent::IsAllowedToSleep , &SHRigidBodyComponent::SetIsAllowedToSleep) .property("Sleeping Enabled" , &SHRigidBodyComponent::IsAllowedToSleep , &SHRigidBodyComponent::SetIsAllowedToSleep)

View File

@ -93,6 +93,7 @@ namespace SHADE
[[nodiscard]] float GetMass () const noexcept; [[nodiscard]] float GetMass () const noexcept;
[[nodiscard]] float GetDrag () const noexcept; [[nodiscard]] float GetDrag () const noexcept;
[[nodiscard]] float GetAngularDrag () const noexcept; [[nodiscard]] float GetAngularDrag () const noexcept;
[[nodiscard]] float GetGravityScale () const noexcept;
[[nodiscard]] SHVec3 GetForce () const noexcept; [[nodiscard]] SHVec3 GetForce () const noexcept;
[[nodiscard]] SHVec3 GetTorque () const noexcept; [[nodiscard]] SHVec3 GetTorque () const noexcept;
@ -123,6 +124,7 @@ namespace SHADE
void SetDrag (float newDrag) noexcept; void SetDrag (float newDrag) noexcept;
void SetAngularDrag (float newAngularDrag) noexcept; void SetAngularDrag (float newAngularDrag) noexcept;
void SetGravityScale (float newGravityScale) noexcept;
void SetLinearVelocity (const SHVec3& newLinearVelocity) noexcept; void SetLinearVelocity (const SHVec3& newLinearVelocity) noexcept;
void SetAngularVelocity (const SHVec3& newAngularVelocity) noexcept; void SetAngularVelocity (const SHVec3& newAngularVelocity) noexcept;
@ -173,6 +175,7 @@ namespace SHADE
// Used for storing serialised data // Used for storing serialised data
uint8_t flags; // aZ aY aX lZ lY lX sleepEnabled gravity uint8_t flags; // aZ aY aX lZ lY lX sleepEnabled gravity
float gravityScale;
float drag; float drag;
float angularDrag; float angularDrag;

View File

@ -11,7 +11,7 @@
#include <SHpch.h> #include <SHpch.h>
// Primary Header // Primary Header
#include "SHPhysicsWorld.h" #include "SHPhysicsWorldState.h"
namespace SHADE namespace SHADE
{ {

View File

@ -1,7 +1,7 @@
/**************************************************************************************** /****************************************************************************************
* \file SHPhysicsWorld.h * \file SHPhysicsWorldState.h
* \author Diren D Bharwani, diren.dbharwani, 390002520 * \author Diren D Bharwani, diren.dbharwani, 390002520
* \brief Interface for a Physics World. * \brief Interface for a Physics World State.
* *
* \copyright Copyright (C) 2022 DigiPen Institute of Technology. Reproduction or * \copyright Copyright (C) 2022 DigiPen Institute of Technology. Reproduction or
* disclosure of this file or its contents without the prior written consent * disclosure of this file or its contents without the prior written consent
@ -14,6 +14,7 @@
// Project Headers // Project Headers
#include "Math/Vector/SHVec3.h" #include "Math/Vector/SHVec3.h"
#include "Physics/SHPhysicsConstants.h"
namespace SHADE namespace SHADE
{ {
@ -37,8 +38,8 @@ namespace SHADE
/*-------------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------------*/
SHVec3 gravity = SHVec3{ 0.0f, -9.81f, 0.0f }; SHVec3 gravity = SHVec3{ 0.0f, -9.81f, 0.0f };
uint16_t numVelocitySolverIterations = 10; uint16_t numVelocitySolverIterations = SHPhysicsConstants::DEFAULT_VELOCITY_ITERATIONS;
uint16_t numPositionSolverIterations = 5; uint16_t numPositionSolverIterations = SHPhysicsConstants::DEFAULT_POSITION_ITERATIONS;
bool sleepingEnabled = true; bool sleepingEnabled = true;
}; };

View File

@ -0,0 +1,23 @@
/****************************************************************************************
* \file SHPhysicsConstants.h
* \author Diren D Bharwani, diren.dbharwani, 390002520
* \brief Declaration of Constants used for physics simulations
*
* \copyright Copyright (C) 2022 DigiPen Institute of Technology. Reproduction or
* disclosure of this file or its contents without the prior written consent
* of DigiPen Institute of Technology is prohibited.
****************************************************************************************/
#pragma once
namespace SHADE
{
struct SHPhysicsConstants
{
static constexpr double DEFAULT_FIXED_DT = 1.0 / 60.0;
static constexpr double DEFAULT_FIXED_UPDATE_RATE = 60.0;
static constexpr int DEFAULT_VELOCITY_ITERATIONS = 10;
static constexpr int DEFAULT_POSITION_ITERATIONS = 5;
};
}

View File

@ -105,14 +105,14 @@ namespace SHADE
* TODO: Test if the scene graph transforms abides by setting world position. Collisions will ignore the scene graph hierarchy. * TODO: Test if the scene graph transforms abides by setting world position. Collisions will ignore the scene graph hierarchy.
*/ */
} }
// Collision & Trigger messages
if (scriptingSystem != nullptr)
scriptingSystem->ExecuteCollisionFunctions();
// Since this function never runs when editor in not in play, execute the function anyway
physicsSystem->collisionListener.CleanContainers();
} }
// Collision & Trigger messages
if (scriptingSystem != nullptr)
scriptingSystem->ExecuteCollisionFunctions();
// Since this function never runs when editor in not in play, execute the function anyway
physicsSystem->collisionListener.CleanContainers();
} }
} // namespace SHADE } // namespace SHADE

View File

@ -17,6 +17,7 @@
#include "ECS_Base/Managers/SHSystemManager.h" #include "ECS_Base/Managers/SHSystemManager.h"
#include "Math/Transform/SHTransformComponent.h" #include "Math/Transform/SHTransformComponent.h"
#include "Physics/SHPhysicsEvents.h" #include "Physics/SHPhysicsEvents.h"
#include "Physics/Collision/Shapes/SHCapsule.h"
#include "Tools/Utilities/SHUtilities.h" #include "Tools/Utilities/SHUtilities.h"
namespace SHADE namespace SHADE
@ -88,11 +89,6 @@ namespace SHADE
} }
void SHPhysicsDebugDrawSystem::AddRaycast(const SHRay& ray, const SHPhysicsRaycastResult& result) noexcept
{
}
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
/* Private Function Member Definitions */ /* Private Function Member Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
@ -139,10 +135,19 @@ namespace SHADE
debugDrawSystem->DrawWireCube(SHAPE->GetTRS(), DRAW_COLOUR, true); debugDrawSystem->DrawWireCube(SHAPE->GetTRS(), DRAW_COLOUR, true);
break; break;
} }
//case SHCollisionShape::Type::CAPSULE: case SHCollisionShape::Type::CAPSULE:
//{ {
// break;
//} const auto* CAPSULE_SHAPE = dynamic_cast<SHCapsule*>(SHAPE);
SHVec3 position, scale;
SHQuaternion rotation;
SHAPE->GetTRS().Decompose(position, rotation, scale);
debugDrawSystem->DrawWireCapsule(position, rotation, CAPSULE_SHAPE->GetWorldHeight(), CAPSULE_SHAPE->GetWorldRadius(), DRAW_COLOUR, true);
break;
}
default: break; default: break;
} }
} }

View File

@ -64,8 +64,6 @@ namespace SHADE
void Init () override; void Init () override;
void Exit () override; void Exit () override;
void AddRaycast (const SHRay& ray, const SHPhysicsRaycastResult& result) noexcept;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* System Routines */ /* System Routines */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
@ -119,13 +117,11 @@ namespace SHADE
/* Data Members */ /* Data Members */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
static constexpr uint8_t ACTIVE_FLAG = 0x01; static constexpr uint8_t ACTIVE_FLAG = 0x01;
static const SHColour DEBUG_DRAW_COLOURS[static_cast<int>(Colours::COUNT)];
static const SHColour DEBUG_DRAW_COLOURS[static_cast<int>(Colours::COUNT)]; // 0 0 0 0 drawRaycasts drawContacts drawAllColliders debugDrawActive
// 0 0 0 drawBroadphase drawRaycasts drawContacts drawAllColliders debugDrawActive
uint8_t flags; uint8_t flags;
Colliders collidersToDraw; Colliders collidersToDraw;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
@ -133,9 +129,7 @@ namespace SHADE
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
SHEventHandle onColliderDraw(SHEventPtr onColliderDrawEvent); SHEventHandle onColliderDraw(SHEventPtr onColliderDrawEvent);
static void drawCollider (SHDebugDrawSystem* debugDrawSystem, const SHColliderComponent& collider) noexcept;
static void drawCollider (SHDebugDrawSystem* debugDrawSystem, const SHColliderComponent& collider) noexcept;
static void drawRaycast (SHDebugDrawSystem* debugDrawSystem, const DebugDrawInfo::Raycast& raycastInfo) noexcept;
}; };

View File

@ -34,7 +34,7 @@ namespace SHADE
SHPhysicsSystem::SHPhysicsSystem() noexcept SHPhysicsSystem::SHPhysicsSystem() noexcept
: worldUpdated { false } : worldUpdated { false }
, interpolationFactor { 0.0 } , interpolationFactor { 0.0 }
, fixedDT { DEFAULT_FIXED_STEP } , fixedDT { SHPhysicsConstants::DEFAULT_FIXED_DT }
{ {
// Add more events here to register them // Add more events here to register them
@ -63,11 +63,6 @@ namespace SHADE
return fixedDT; return fixedDT;
} }
double SHPhysicsSystem::GetDefaultFixedDT() const noexcept
{
return DEFAULT_FIXED_STEP;
}
const std::vector<SHCollisionInfo>& SHPhysicsSystem::GetAllCollisionInfo() const noexcept const std::vector<SHCollisionInfo>& SHPhysicsSystem::GetAllCollisionInfo() const noexcept
{ {
return collisionListener.GetCollisionInfoContainer(); return collisionListener.GetCollisionInfoContainer();
@ -78,6 +73,26 @@ namespace SHADE
return collisionListener.GetTriggerInfoContainer(); return collisionListener.GetTriggerInfoContainer();
} }
const SHVec3& SHPhysicsSystem::GetGravity() const noexcept
{
return worldState.settings.gravity;
}
uint16_t SHPhysicsSystem::GetNumVelocityIterations() const noexcept
{
return worldState.settings.numVelocitySolverIterations;
}
uint16_t SHPhysicsSystem::GetNumPositionIterations() const noexcept
{
return worldState.settings.numPositionSolverIterations;
}
bool SHPhysicsSystem::IsSleepingEnabled() const noexcept
{
return worldState.settings.sleepingEnabled;
}
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
/* Setter Function Definitions */ /* Setter Function Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
@ -117,6 +132,30 @@ namespace SHADE
} }
} }
void SHPhysicsSystem::SetGravity(const SHVec3& gravity) noexcept
{
worldState.settings.gravity = gravity;
worldState.UpdateSettings();
}
void SHPhysicsSystem::SetNumVelocityIterations(uint16_t value) noexcept
{
worldState.settings.numVelocitySolverIterations = value;
worldState.UpdateSettings();
}
void SHPhysicsSystem::SetNumPositionIterations(uint16_t value) noexcept
{
worldState.settings.numPositionSolverIterations = value;
worldState.UpdateSettings();
}
void SHPhysicsSystem::EnableSleeping(bool sleepingAllowed) noexcept
{
worldState.settings.sleepingEnabled = sleepingAllowed;
worldState.UpdateSettings();
}
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
/* Public Function Member Definitions */ /* Public Function Member Definitions */
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
@ -172,6 +211,159 @@ namespace SHADE
return results; return results;
} }
bool SHPhysicsSystem::TestAABBOverlap(const SHAABB& aabb, uint16_t layers)
{
if (!worldState.world)
{
SHLOG_ERROR("Cannot test AABB overlap without a physics world!")
return false;
}
// Create a temporary collider to test against the world
auto* tempRP3DBody = worldState.world->createCollisionBody(rp3d::Transform { aabb.GetCenter(), SHQuaternion::Identity });
auto* tempRP3DBox = factory.createBoxShape(aabb.GetExtents());
auto* tempRP3DCollider = tempRP3DBody->addCollider(tempRP3DBox, rp3d::Transform{});
tempRP3DCollider->setCollisionCategoryBits(layers);
tempRP3DCollider->setCollideWithMaskBits(layers);
// Test the temp collider against the world
const bool IS_COLLIDING = worldState.world->testOverlap(tempRP3DBody);
tempRP3DBody->removeCollider(tempRP3DCollider);
factory.destroyBoxShape(tempRP3DBox);
worldState.world->destroyCollisionBody(tempRP3DBody);
return IS_COLLIDING;
}
void SHPhysicsSystem::SimulateBody(std::vector<SHVec3>& positions, std::vector<SHQuaternion>& orientations, const SimulateBodyInfo& simInfo)
{
// Check for a valid rigidbody
const auto* rigidBody = SHComponentManager::GetComponent_s<SHRigidBodyComponent>(simInfo.bodyEID);
if (!rigidBody)
{
SHLOG_WARNING("Entity {} does not have a rigid body to simulate!", simInfo.bodyEID)
return;
}
// Ignore non-dynamic bodies
if (rigidBody->type != SHRigidBodyComponent::Type::DYNAMIC)
{
SHLOG_WARNING("Entity {} is not a dynamic body. We cannot simulate non-dynamic bodies!", simInfo.bodyEID)
return;
}
// Prepare simulation info (I'm basically declaring an entire body here)
SHVec3 bodyPosition = rigidBody->GetPosition();
SHQuaternion bodyOrientation = SHQuaternion::FromEuler(rigidBody->GetRotation());
SHVec3 linearVelocity = rigidBody->GetLinearVelocity();
SHVec3 angularVelocity = rigidBody->GetAngularVelocity();
float invMass = 1.0f / rigidBody->GetMass();
SHVec3 localInvInertia = rigidBody->rigidBody->getLocalInertiaTensor();
SHVec3 worldInvInertia = SHVec3::One;
SHVec3 localCentroid = rigidBody->rigidBody->getLocalCenterOfMass();
SHVec3 worldCentroid = SHVec3::One;
SHVec3 appliedForce = simInfo.force;
SHVec3 appliedTorque = simInfo.torque;
SHVec3 accumulatedForce = SHVec3::Zero;
SHVec3 accumulatedTorque = SHVec3::Zero;
const SHVec3& LINEAR_LOCK = rigidBody->rigidBody->getLinearLockAxisFactor();
const SHVec3& ANGULAR_LOCK = rigidBody->rigidBody->getAngularLockAxisFactor();
// Invert the inertia
for (size_t i = 0; i < SHVec3::SIZE; ++i)
localInvInertia[i] = 1.0f / localInvInertia[i];
// Build raycast layer from colliders. If none exist....then this never stops simulating technically.
// I'm too lazy to handle that case, so I'll just throw an error.
uint16_t raycastLayers = 0;
if (const auto* colliders = SHComponentManager::GetComponent_s<SHColliderComponent>(simInfo.bodyEID); colliders)
{
const auto& shapes = colliders->GetCollisionShapes();
for (auto& shape : shapes)
raycastLayers |= shape->GetCollisionTag().GetMask();
}
else
{
SHLOG_WARNING("Unable to simulate body {} without a collider (it will simulate forever!)", simInfo.bodyEID)
return;
}
// Raycast direction is always in the direction of the linear velocity
// Raycast distance is the length of the velocity
SHRaycaster::RaycastInfo raycastInfo;
raycastInfo.continuous = false;
raycastInfo.layers = raycastLayers;
bool terminate = true;
do
{
raycastInfo.distance = linearVelocity.Length();
raycastInfo.ray.position = bodyPosition;
raycastInfo.ray.direction = SHVec3::Normalise(linearVelocity);
terminate = !Raycast(raycastInfo).empty();
if (terminate)
break;
// Compute world space data
const SHMatrix R = SHMatrix::Rotate(bodyOrientation);
const SHMatrix RT = SHMatrix::Transpose(R);
SHMatrix localInertiaTensor = SHMatrix::Identity;
// Set the diagonals
localInertiaTensor.m[0][0] = localInvInertia.x;
localInertiaTensor.m[1][1] = localInvInertia.y;
localInertiaTensor.m[2][2] = localInvInertia.z;
localInertiaTensor *= RT;
const SHVec3 DIAGONALS { localInertiaTensor.m[0][0], localInertiaTensor.m[1][1], localInertiaTensor.m[2][2] };
worldInvInertia = R * DIAGONALS;
// Compute world centroid
worldCentroid = (R * localCentroid) + bodyPosition;
// Apply forces
accumulatedForce += appliedForce;
angularVelocity += worldInvInertia * SHVec3::Cross(bodyPosition + simInfo.forceOffset, simInfo.force);
accumulatedTorque += appliedTorque;
// Integrate Velocities
// Integrate forces and gravity into linear velocity
const SHVec3 LINEAR_ACCELERATION = accumulatedForce * invMass;
const SHVec3 GRAVITATIONAL_ACCELERATION = rigidBody->IsGravityEnabled() ? worldState.settings.gravity * rigidBody->GetGravityScale() : SHVec3::Zero;
linearVelocity += (LINEAR_ACCELERATION + GRAVITATIONAL_ACCELERATION) * simInfo.timeStep * LINEAR_LOCK;
angularVelocity += worldInvInertia * (accumulatedTorque * simInfo.timeStep);
// Apply drag (exponentially applied)
linearVelocity *= 1.0f / (1.0f + simInfo.timeStep * rigidBody->drag);
angularVelocity *= 1.0f / (1.0f + simInfo.timeStep * rigidBody->angularDrag);
// Integrate Positions & Orientations
const SHQuaternion QV = SHQuaternion{ angularVelocity.x * simInfo.timeStep, angularVelocity.y * simInfo.timeStep, angularVelocity.z * simInfo.timeStep, 0.0f } * 0.5f;
bodyPosition += linearVelocity * simInfo.timeStep;
bodyOrientation += bodyOrientation * QV;
bodyOrientation = SHQuaternion::Normalise(bodyOrientation);
// Clear forces after the first frame
if (!simInfo.continuousForce)
{
accumulatedForce = SHVec3::Zero;
accumulatedTorque = SHVec3::Zero;
appliedForce = SHVec3::Zero;
appliedTorque = SHVec3::Zero;
}
positions.emplace_back(bodyPosition);
} while (true);
}
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
/* Private Function Member Definitions */ /* Private Function Member Definitions */

View File

@ -18,9 +18,10 @@
// Project Headers // Project Headers
#include "ECS_Base/System/SHSystemRoutine.h" #include "ECS_Base/System/SHSystemRoutine.h"
#include "ECS_Base/System/SHFixedSystemRoutine.h" #include "ECS_Base/System/SHFixedSystemRoutine.h"
#include "Math/Geometry/SHAABB.h"
#include "Physics/Collision/SHCollisionInfo.h" #include "Physics/Collision/SHCollisionInfo.h"
#include "Physics/Interface/PhysicsObject/SHPhysicsObjectManager.h" #include "Physics/Interface/PhysicsObject/SHPhysicsObjectManager.h"
#include "Physics/RP3DWrapper/SHPhysicsWorld.h" #include "Physics/RP3DWrapper/SHPhysicsWorldState.h"
#include "Physics/RP3DWrapper/SHCollisionListener.h" #include "Physics/RP3DWrapper/SHCollisionListener.h"
#include "Physics/RP3DWrapper/SHRaycaster.h" #include "Physics/RP3DWrapper/SHRaycaster.h"
#include "Scene/SHSceneGraph.h" #include "Scene/SHSceneGraph.h"
@ -43,32 +44,63 @@ namespace SHADE
friend class SHRaycaster; friend class SHRaycaster;
public: public:
/*---------------------------------------------------------------------------------*/
/* Type Definitions */
/*---------------------------------------------------------------------------------*/
/**
* @brief
* Used to simulate the motion of a rigid body until it hits something.
*/
struct SimulateBodyInfo
{
EntityID bodyEID = MAX_EID;
SHVec3 force = SHVec3::Zero;
SHVec3 forceOffset = SHVec3::Zero;
SHVec3 torque = SHVec3::Zero;
// Whether or not to clear the force after the first iteration
bool continuousForce = false;
float timeStep = static_cast<float>(SHPhysicsConstants::DEFAULT_FIXED_DT);
};
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Constructors & Destructor */ /* Constructors & Destructor */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
SHPhysicsSystem () noexcept; SHPhysicsSystem () noexcept;
~SHPhysicsSystem() noexcept; ~SHPhysicsSystem() noexcept override;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Getter Functions */ /* Getter Functions */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
[[nodiscard]] double GetFixedUpdateRate () const noexcept; [[nodiscard]] double GetFixedUpdateRate () const noexcept;
[[nodiscard]] double GetFixedDT () const noexcept; [[nodiscard]] double GetFixedDT () const noexcept;
[[nodiscard]] double GetDefaultFixedDT () const noexcept;
[[nodiscard]] const std::vector<SHCollisionInfo>& GetAllTriggerInfo () const noexcept; [[nodiscard]] const std::vector<SHCollisionInfo>& GetAllTriggerInfo () const noexcept;
[[nodiscard]] const std::vector<SHCollisionInfo>& GetAllCollisionInfo () const noexcept; [[nodiscard]] const std::vector<SHCollisionInfo>& GetAllCollisionInfo () const noexcept;
// World Settings
[[nodiscard]] const SHVec3& GetGravity () const noexcept;
[[nodiscard]] uint16_t GetNumVelocityIterations () const noexcept;
[[nodiscard]] uint16_t GetNumPositionIterations () const noexcept;
[[nodiscard]] bool IsSleepingEnabled () const noexcept;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Setter Functions */ /* Setter Functions */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
void SetFixedUpdateRate (double fixedUpdateRate) noexcept; void SetFixedUpdateRate (double fixedUpdateRate) noexcept;
void SetFixedDT (double fixedDt) noexcept; void SetFixedDT (double fixedDt) noexcept;
void SetGravity (const SHVec3& gravity) noexcept;
void SetNumVelocityIterations (uint16_t value) noexcept;
void SetNumPositionIterations (uint16_t value) noexcept;
void EnableSleeping (bool sleepingAllowed) noexcept;
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Function Members */ /* Function Members */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
@ -92,6 +124,30 @@ namespace SHADE
*/ */
[[nodiscard]] const std::vector<SHPhysicsRaycastResult>& Raycast(const SHRaycaster::RaycastInfo& info) noexcept; [[nodiscard]] const std::vector<SHPhysicsRaycastResult>& Raycast(const SHRaycaster::RaycastInfo& info) noexcept;
/**
* \brief
* Tests if an AABB overlaps with anything in the scene.
* \param aabb
* The AABB to test.
* \param layers
* The layer(s) to test the overlap on. Defaults to all layers.
* \return
* True if there is any overlap.
*/
[[nodiscard]] bool TestAABBOverlap(const SHAABB& aabb, uint16_t layers = static_cast<uint16_t>(SHCollisionTag::Layer::ALL));
/**
* @brief
* Simulates the motion of a body until it collides with something.
* @param positions
* The output vector for the position of the body in each timestep.
* @param orientations
* The output vector for the orientations of the body in each timestep.
* @param simInfo
* The information for simulating the body.
*/
void SimulateBody(std::vector<SHVec3>& positions, std::vector<SHQuaternion>& orientations, const SimulateBodyInfo& simInfo);
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* System Routines */ /* System Routines */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/

View File

@ -60,24 +60,7 @@ namespace SHADE
return 0.0; return 0.0;
} }
double SHPhysicsSystemInterface::GetDeafultFixedDT() noexcept
{
auto* physicsSystem = SHSystemManager::GetSystem<SHPhysicsSystem>();
if (physicsSystem)
return physicsSystem->GetDefaultFixedDT();
SHLOGV_WARNING("Failed to get defualt fixed delta time. 0.0 returned instead.");
return 0.0;
}
void SHPhysicsSystemInterface::SetFixedDT(double value) noexcept
{
auto* physicsSystem = SHSystemManager::GetSystem<SHPhysicsSystem>();
if (physicsSystem)
physicsSystem->SetFixedDT(value);
SHLOGV_WARNING("Failed to set fixed delta time.");
}
int SHPhysicsSystemInterface::GetFixedUpdateRate() noexcept int SHPhysicsSystemInterface::GetFixedUpdateRate() noexcept
{ {
@ -89,6 +72,100 @@ namespace SHADE
return 0.0; return 0.0;
} }
SHVec3 SHPhysicsSystemInterface::GetGravity() noexcept
{
auto* physicsSystem = SHSystemManager::GetSystem<SHPhysicsSystem>();
if (physicsSystem)
return physicsSystem->GetGravity();
SHLOGV_WARNING("Failed to get gravity. Zero Vec3 returned instead.");
return SHVec3::Zero;
}
uint16_t SHPhysicsSystemInterface::GetNumVelocityIterations() noexcept
{
auto* physicsSystem = SHSystemManager::GetSystem<SHPhysicsSystem>();
if (physicsSystem)
return physicsSystem->GetNumVelocityIterations();
SHLOGV_WARNING("Failed to get number of velocity iterations. 0 returned instead.");
return 0;
}
uint16_t SHPhysicsSystemInterface::GetNumPositionIterations() noexcept
{
auto* physicsSystem = SHSystemManager::GetSystem<SHPhysicsSystem>();
if (physicsSystem)
return physicsSystem->GetNumPositionIterations();
SHLOGV_WARNING("Failed to get number of position iterations. 0 returned instead.");
return 0;
}
bool SHPhysicsSystemInterface::IsSleepingEnabled() noexcept
{
auto* physicsSystem = SHSystemManager::GetSystem<SHPhysicsSystem>();
if (physicsSystem)
return physicsSystem->IsSleepingEnabled();
SHLOGV_WARNING("Failed to check if sleeping is enabled. False returned instead.");
return false;
}
void SHPhysicsSystemInterface::SetFixedDT(double fixedDT) noexcept
{
auto* physicsSystem = SHSystemManager::GetSystem<SHPhysicsSystem>();
if (physicsSystem)
physicsSystem->SetFixedDT(fixedDT);
SHLOGV_WARNING("Failed to set fixed delta time.");
}
void SHPhysicsSystemInterface::SetFixedUpdateRate(double fixedUpdateRate) noexcept
{
auto* physicsSystem = SHSystemManager::GetSystem<SHPhysicsSystem>();
if (physicsSystem)
return physicsSystem->SetFixedUpdateRate(fixedUpdateRate);
SHLOGV_WARNING("Failed to set fixed update rate.");
}
void SHPhysicsSystemInterface::SetGravity(const SHVec3& gravity) noexcept
{
auto* physicsSystem = SHSystemManager::GetSystem<SHPhysicsSystem>();
if (physicsSystem)
return physicsSystem->SetGravity(gravity);
SHLOGV_WARNING("Failed to set gravity.");
}
void SHPhysicsSystemInterface::SetNumVelocityIterations(uint16_t value) noexcept
{
auto* physicsSystem = SHSystemManager::GetSystem<SHPhysicsSystem>();
if (physicsSystem)
return physicsSystem->SetNumVelocityIterations(value);
SHLOGV_WARNING("Failed to set number of velocity iterations.");
}
void SHPhysicsSystemInterface::SetNumPositionIterations(uint16_t value) noexcept
{
auto* physicsSystem = SHSystemManager::GetSystem<SHPhysicsSystem>();
if (physicsSystem)
return physicsSystem->SetNumPositionIterations(value);
SHLOGV_WARNING("Failed to set number of position iterations.");
}
void SHPhysicsSystemInterface::EnableSleeping(bool sleepingAllowed) noexcept
{
auto* physicsSystem = SHSystemManager::GetSystem<SHPhysicsSystem>();
if (physicsSystem)
return physicsSystem->EnableSleeping(sleepingAllowed);
SHLOGV_WARNING("Failed to set global sleeping state.");
}
const std::vector<SHPhysicsRaycastResult>& SHPhysicsSystemInterface::Raycast(const RaycastInfo& info) noexcept const std::vector<SHPhysicsRaycastResult>& SHPhysicsSystemInterface::Raycast(const RaycastInfo& info) noexcept
{ {
static std::vector<SHPhysicsRaycastResult> emptyVec; static std::vector<SHPhysicsRaycastResult> emptyVec;

View File

@ -90,13 +90,23 @@ namespace SHADE
/* Static Usage Functions */ /* Static Usage Functions */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
[[nodiscard]] static const std::vector<SHCollisionInfo>& GetCollisionInfo () noexcept; [[nodiscard]] static const std::vector<SHCollisionInfo>& GetCollisionInfo () noexcept;
[[nodiscard]] static const std::vector<SHCollisionInfo>& GetTriggerInfo () noexcept; [[nodiscard]] static const std::vector<SHCollisionInfo>& GetTriggerInfo () noexcept;
[[nodiscard]] static double GetFixedDT () noexcept; [[nodiscard]] static double GetFixedDT () noexcept;
[[nodiscard]] static void SetFixedDT (double value) noexcept; [[nodiscard]] static int GetFixedUpdateRate () noexcept;
[[nodiscard]] static double GetDeafultFixedDT () noexcept; [[nodiscard]] static SHVec3 GetGravity () noexcept;
[[nodiscard]] static int GetFixedUpdateRate () noexcept; [[nodiscard]] static uint16_t GetNumVelocityIterations () noexcept;
[[nodiscard]] static const std::vector<SHPhysicsRaycastResult>& Raycast (const RaycastInfo& info) noexcept; [[nodiscard]] static uint16_t GetNumPositionIterations () noexcept;
[[nodiscard]] static bool IsSleepingEnabled () noexcept;
static void SetFixedDT (double fixedDT) noexcept;
static void SetFixedUpdateRate (double fixedUpdateRate) noexcept;
static void SetGravity (const SHVec3& gravity) noexcept;
static void SetNumVelocityIterations (uint16_t value) noexcept;
static void SetNumPositionIterations (uint16_t value) noexcept;
static void EnableSleeping (bool sleepingAllowed) noexcept;
[[nodiscard]] static const std::vector<SHPhysicsRaycastResult>& Raycast (const RaycastInfo& info) noexcept;
}; };
} }

View File

@ -16,6 +16,7 @@
#include "Animation/SHAnimatorComponent.h" #include "Animation/SHAnimatorComponent.h"
#include "Physics/Collision/CollisionTags/SHCollisionTagMatrix.h" #include "Physics/Collision/CollisionTags/SHCollisionTagMatrix.h"
#include "Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.h" #include "Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.h"
#include "Physics/Collision/Shapes/SHCapsule.h"
namespace YAML namespace YAML
{ {
@ -127,6 +128,7 @@ namespace YAML
static constexpr const char* Type = "Type"; static constexpr const char* Type = "Type";
static constexpr const char* HalfExtents = "Half Extents"; static constexpr const char* HalfExtents = "Half Extents";
static constexpr const char* Radius = "Radius"; static constexpr const char* Radius = "Radius";
static constexpr const char* Height = "Height";
static constexpr const char* Friction = "Friction"; static constexpr const char* Friction = "Friction";
static constexpr const char* Bounciness = "Bounciness"; static constexpr const char* Bounciness = "Bounciness";
@ -161,7 +163,13 @@ namespace YAML
node[Radius] = SPHERE_SHAPE.GetRelativeRadius(); node[Radius] = SPHERE_SHAPE.GetRelativeRadius();
} }
break; break;
//case SHCollisionShape::Type::CAPSULE: break; case SHCollisionShape::Type::CAPSULE:
{
const auto& CAPSULE_SHAPE = dynamic_cast<SHCapsule&>(rhs);
node[Radius] = CAPSULE_SHAPE.GetRelativeRadius();
node[Height] = CAPSULE_SHAPE.GetRelativeHeight();
}
break;
default:; default:;
} }
@ -203,7 +211,17 @@ namespace YAML
dynamic_cast<SHSphere&>(rhs).SetRelativeRadius(node[Radius].as<float>()); dynamic_cast<SHSphere&>(rhs).SetRelativeRadius(node[Radius].as<float>());
} }
break; break;
//case SHCollisionShape::Type::CAPSULE: break; case SHCollisionShape::Type::CAPSULE:
{
auto& capsule = dynamic_cast<SHCapsule&>(rhs);
if (node[Radius].IsDefined())
capsule.SetRelativeRadius(node[Radius].as<float>());
if (node[Height].IsDefined())
capsule.SetRelativeHeight(node[Height].as<float>());
}
break;
default:; default:;
} }
if (node[Friction].IsDefined()) if (node[Friction].IsDefined())
@ -258,7 +276,7 @@ namespace YAML
{ {
case SHCollisionShape::Type::BOX: rhs.AddBoxCollisionShape(SHVec3::One); break; case SHCollisionShape::Type::BOX: rhs.AddBoxCollisionShape(SHVec3::One); break;
case SHCollisionShape::Type::SPHERE: rhs.AddSphereCollisionShape(1.0f); break; case SHCollisionShape::Type::SPHERE: rhs.AddSphereCollisionShape(1.0f); break;
//case SHCollisionShape::Type::CAPSULE: break; case SHCollisionShape::Type::CAPSULE: rhs.AddCapsuleCollisionShape(1.0f, 2.0f); break;
default:; default:;
} }
YAML::convert<SHCollisionShape>::decode(colliderNode, rhs.GetCollisionShape(numColliders++)); YAML::convert<SHCollisionShape>::decode(colliderNode, rhs.GetCollisionShape(numColliders++));

View File

@ -17,6 +17,7 @@ of DigiPen Institute of Technology is prohibited.
// External Dependencies // External Dependencies
#include "FRC/SHFramerateController.h" #include "FRC/SHFramerateController.h"
#include "Physics/System/SHPhysicsSystemInterface.h" #include "Physics/System/SHPhysicsSystemInterface.h"
#include "Physics/SHPhysicsConstants.h"
// Primary Header // Primary Header
#include "Time.hxx" #include "Time.hxx"
@ -47,7 +48,6 @@ namespace SHADE
double Time::DefaultFixDeltaTime::get() double Time::DefaultFixDeltaTime::get()
{ {
return SHPhysicsSystemInterface::GetDeafultFixedDT(); return SHPhysicsConstants::DEFAULT_FIXED_DT;
} }
} }

View File

@ -31,14 +31,42 @@ namespace SHADE
Vector3 Physics::Gravity::get() Vector3 Physics::Gravity::get()
{ {
// TODO(Diren) return Convert::ToCLI(SHPhysicsSystemInterface::GetGravity());
return Vector3::Zero;
} }
void Physics::Gravity::set(Vector3 value) void Physics::Gravity::set(Vector3 value)
{ {
(void)value; SHPhysicsSystemInterface::SetGravity(Convert::ToNative(value));
}
uint16_t Physics::VelocityIterations::get()
{
return SHPhysicsSystemInterface::GetNumVelocityIterations();
}
void Physics::VelocityIterations::set(uint16_t value)
{
SHPhysicsSystemInterface::SetNumVelocityIterations(value);
}
uint16_t Physics::PositionIterations::get()
{
return SHPhysicsSystemInterface::GetNumPositionIterations();
}
void Physics::PositionIterations::set(uint16_t value)
{
SHPhysicsSystemInterface::SetNumPositionIterations(value);
}
bool Physics::SleepingEnabled::get()
{
return SHPhysicsSystemInterface::IsSleepingEnabled();
}
void Physics::SleepingEnabled::set(bool value)
{
SHPhysicsSystemInterface::EnableSleeping(value);
} }
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/

View File

@ -33,7 +33,23 @@ namespace SHADE
void set(Vector3 value); void set(Vector3 value);
} }
// TODO(Diren): Add more properties for physics system settings. static property uint16_t VelocityIterations
{
uint16_t get();
void set(uint16_t value);
}
static property uint16_t PositionIterations
{
uint16_t get();
void set(uint16_t value);
}
static property bool SleepingEnabled
{
bool get();
void set(bool value);
}
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Raycast Function Members */ /* Raycast Function Members */