From 357b36a9b085cf08c0caf5b190081f48f329525d Mon Sep 17 00:00:00 2001 From: Diren D Bharwani Date: Tue, 27 Sep 2022 16:24:08 +0800 Subject: [PATCH 01/17] Added RigidBody Component --- SHADE_Engine/src/Math/SHMathHelpers.hpp | 2 +- .../Math/Transform/SHTransformComponent.cpp | 37 -- .../src/Math/Transform/SHTransformComponent.h | 8 +- .../Components/SHRigidBodyComponent.cpp | 499 ++++++++++++++++++ .../Physics/Components/SHRigidBodyComponent.h | 147 ++++++ SHADE_Engine/src/SHpch.h | 1 + SHADE_Engine/src/Tools/SHException.h | 17 +- 7 files changed, 662 insertions(+), 49 deletions(-) create mode 100644 SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp create mode 100644 SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h diff --git a/SHADE_Engine/src/Math/SHMathHelpers.hpp b/SHADE_Engine/src/Math/SHMathHelpers.hpp index 0e5fc5fa..d95bcfa2 100644 --- a/SHADE_Engine/src/Math/SHMathHelpers.hpp +++ b/SHADE_Engine/src/Math/SHMathHelpers.hpp @@ -120,7 +120,7 @@ namespace SHADE bool SHMath::CompareFloat(T lhs, T rhs, T absTolerance, T relTolerance) { const T RTOL = relTolerance * Max(std::fabs(lhs), std::fabs(rhs)); - return std::fabs(lhs - rhs) <= MAX(absTolerance, RTOL); + return std::fabs(lhs - rhs) <= Max(absTolerance, RTOL); } } // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp b/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp index cdc5105f..fd950628 100644 --- a/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp +++ b/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp @@ -24,43 +24,6 @@ namespace SHADE , dirty { true } {} - SHTransformComponent::SHTransformComponent(const SHTransformComponent& rhs) noexcept - : SHComponent {} - , dirty { true } - , local { rhs.local } - , world { rhs.world } - {} - - SHTransformComponent::SHTransformComponent(SHTransformComponent&& rhs) noexcept - : SHComponent {} - , dirty { true } - , local { std::move(rhs.local) } - , world { std::move(rhs.world) } - {} - - /*-----------------------------------------------------------------------------------*/ - /* Operator Overload Definitions */ - /*-----------------------------------------------------------------------------------*/ - - SHTransformComponent& SHTransformComponent::operator=(const SHTransformComponent& rhs) noexcept - { - dirty = true; - local = rhs.local; - world = rhs.world; - - return *this; - } - - SHTransformComponent& SHTransformComponent::operator=(SHTransformComponent&& rhs) noexcept - { - dirty = true; - local = std::move(rhs.local); - world = std::move(rhs.world); - - return *this; - } - - /*-----------------------------------------------------------------------------------*/ /* Getter Function Definitions */ /*-----------------------------------------------------------------------------------*/ diff --git a/SHADE_Engine/src/Math/Transform/SHTransformComponent.h b/SHADE_Engine/src/Math/Transform/SHTransformComponent.h index 7f7dd473..50377b3a 100644 --- a/SHADE_Engine/src/Math/Transform/SHTransformComponent.h +++ b/SHADE_Engine/src/Math/Transform/SHTransformComponent.h @@ -40,15 +40,15 @@ namespace SHADE ~SHTransformComponent () override = default; SHTransformComponent () noexcept; - SHTransformComponent (const SHTransformComponent& rhs) noexcept; - SHTransformComponent (SHTransformComponent&& rhs) noexcept; + SHTransformComponent (const SHTransformComponent& rhs) noexcept = default; + SHTransformComponent (SHTransformComponent&& rhs) noexcept = default; /*---------------------------------------------------------------------------------*/ /* Operator Overloads */ /*---------------------------------------------------------------------------------*/ - SHTransformComponent& operator=(const SHTransformComponent& rhs) noexcept; - SHTransformComponent& operator=(SHTransformComponent&& rhs) noexcept; + SHTransformComponent& operator=(const SHTransformComponent& rhs) noexcept = default; + SHTransformComponent& operator=(SHTransformComponent&& rhs) noexcept = default; /*---------------------------------------------------------------------------------*/ /* Getter Functions */ diff --git a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp new file mode 100644 index 00000000..2de6e52a --- /dev/null +++ b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp @@ -0,0 +1,499 @@ +/**************************************************************************************** + * \file SHRigidBodyComponent.cpp + * \author Diren D Bharwani, diren.dbharwani, 390002520 + * \brief Implementation for a Rigidbody Component. + * + * \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 + +// Primary Header +#include "SHRigidBodyComponent.h" + +// Project Headers +#include "Tools/SHUtilities.h" +#include "Math/SHMathHelpers.h" +#include "Math/SHQuaternion.h" + +/*-------------------------------------------------------------------------------------*/ +/* Local Function Definitions */ +/*-------------------------------------------------------------------------------------*/ + + + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Constructors & Destructor Definitions */ + /*-----------------------------------------------------------------------------------*/ + + SHRigidBodyComponent::SHRigidBodyComponent() noexcept + : rigidBody { nullptr } + , type { Type::DYNAMIC } + , mass { 1.0f } + , drag { 0.01f } + , angularDrag { 0.01f } + , flags { 0 } + { + // Set default flags: Gravity & Sleeping enabled + flags |= 1U << 0; + flags |= 1U << 1; + + // TODO(Diren): Send an update command to the physics system + } + + SHRigidBodyComponent::~SHRigidBodyComponent() + { + rigidBody = nullptr; + } + + /*-----------------------------------------------------------------------------------*/ + /* Getter Function Definitions */ + /*-----------------------------------------------------------------------------------*/ + + bool SHRigidBodyComponent::IsGravityEnabled() const noexcept + { + const bool GRAVITY = flags & (1U << 0); + if (rigidBody) + { + SHASSERT(rigidBody->isGravityEnabled() == GRAVITY, "ReactPhysics and SHADE body enable gravity do not match!") + } + + return GRAVITY; + } + + bool SHRigidBodyComponent::IsSleepingEnabled() const noexcept + { + const bool SLEEP = flags & (1U << 1); + if (rigidBody) + { + SHASSERT(rigidBody->isAllowedToSleep() == SLEEP, "ReactPhysics and SHADE body enable sleep do not match!") + } + + return SLEEP; + } + + SHRigidBodyComponent::Type SHRigidBodyComponent::GetType() const noexcept + { + if (rigidBody) + { + SHASSERT + ( + SHUtilities::ConvertEnum(rigidBody->getType()) == SHUtilities::ConvertEnum(type), + "ReactPhysics and SHADE body types do not match!" + ) + } + + return type; + } + + float SHRigidBodyComponent::GetMass() const noexcept + { + if (rigidBody) + { + SHASSERT(rigidBody->getMass() == mass, "ReactPhysics and SHADE body masses do not match!") + } + + return mass; + } + + float SHRigidBodyComponent::GetDrag() const noexcept + { + if (rigidBody) + { + SHASSERT + ( + SHMath::CompareFloat(rigidBody->getLinearDamping(), drag), + "ReactPhysics and SADE body drag coefficients do not match!" + ) + } + + return drag; + } + + float SHRigidBodyComponent::GetAngularDrag() const noexcept + { + if (rigidBody) + { + SHASSERT + ( + SHMath::CompareFloat(rigidBody->getAngularDamping(), angularDrag), + "ReactPhysics and SADE body drag coefficients do not match!" + ) + } + + return angularDrag; + } + + bool SHRigidBodyComponent::GetFreezePositionX() const noexcept + { + const bool FREEZE_X_POS = flags & (1U << 2); + if (rigidBody) + { + const bool RP3D_FREEZE_X_POS = fabs(rigidBody->getLinearLockAxisFactor().x) > 0.0f; + SHASSERT(RP3D_FREEZE_X_POS == FREEZE_X_POS, "ReactPhysics and SHADE body x-axis position lock do not match!") + } + + return FREEZE_X_POS; + } + + bool SHRigidBodyComponent::GetFreezePositionY() const noexcept + { + const bool FREEZE_Y_POS = flags & (1U << 3); + if (rigidBody) + { + const bool RP3D_FREEZE_Y_POS = fabs(rigidBody->getLinearLockAxisFactor().y) > 0.0f; + SHASSERT(RP3D_FREEZE_Y_POS == FREEZE_Y_POS, "ReactPhysics and SHADE body y-axis position lock do not match!") + } + + return FREEZE_Y_POS; + } + + bool SHRigidBodyComponent::GetFreezePositionZ() const noexcept + { + const bool FREEZE_Z_POS = flags & (1U << 4); + if (rigidBody) + { + const bool RP3D_FREEZE_Z_POS = fabs(rigidBody->getLinearLockAxisFactor().z) > 0.0f; + SHASSERT(RP3D_FREEZE_Z_POS == FREEZE_Z_POS, "ReactPhysics and SHADE body z-axis position lock do not match!") + } + + return FREEZE_Z_POS; + } + + bool SHRigidBodyComponent::GetFreezeRotationX() const noexcept + { + const bool FREEZE_X_ROT = flags & (1U << 5); + if (rigidBody) + { + const bool RP3D_FREEZE_Y_ROT = fabs(rigidBody->getAngularLockAxisFactor().x) > 0.0f; + SHASSERT(RP3D_FREEZE_Y_ROT == FREEZE_X_ROT, "ReactPhysics and SHADE body x-axis rotation lock do not match!") + } + + return FREEZE_X_ROT; + } + + bool SHRigidBodyComponent::GetFreezeRotationY() const noexcept + { + const bool FREEZE_Y_ROT = flags & (1U << 6); + if (rigidBody) + { + const bool RP3D_FREEZE_Y_ROT = fabs(rigidBody->getAngularLockAxisFactor().y) > 0.0f; + SHASSERT(RP3D_FREEZE_Y_ROT == FREEZE_Y_ROT, "ReactPhysics and SHADE body y-axis rotation lock do not match!") + } + + return FREEZE_Y_ROT; + } + + bool SHRigidBodyComponent::GetFreezeRotationZ() const noexcept + { + const bool FREEZE_Z_ROT = flags & (1U << 7); + if (rigidBody) + { + const bool RP3D_FREEZE_Z_ROT = fabs(rigidBody->getAngularLockAxisFactor().z) > 0.0f; + SHASSERT(RP3D_FREEZE_Z_ROT == FREEZE_Z_ROT, "ReactPhysics and SHADE body z-axis rotation lock do not match!") + } + + return FREEZE_Z_ROT; + } + + SHVec3 SHRigidBodyComponent::GetForce() const noexcept + { + SHVec3 result; + + if (rigidBody) + { + const auto RP3D_RESULT = rigidBody->getForce(); + result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z }; + } + + return result; + } + + SHVec3 SHRigidBodyComponent::GetTorque() const noexcept + { + SHVec3 result; + + if (rigidBody) + { + const auto RP3D_RESULT = rigidBody->getTorque(); + result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z }; + } + + return result; + } + + SHVec3 SHRigidBodyComponent::GetLinearVelocity() const noexcept + { + SHVec3 result; + + if (rigidBody) + { + const auto RP3D_RESULT = rigidBody->getLinearVelocity(); + result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z }; + } + + return result; + } + + SHVec3 SHRigidBodyComponent::GetAngularVelocity() const noexcept + { + SHVec3 result; + + if (rigidBody) + { + const auto RP3D_RESULT = rigidBody->getAngularVelocity(); + result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z }; + } + + return result; + } + + SHVec3 SHRigidBodyComponent::GetPosition() const noexcept + { + SHVec3 result; + + if (rigidBody) + { + const auto RP3D_RESULT = rigidBody->getTransform().getPosition(); + result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z }; + } + + return result; + } + + SHQuaternion SHRigidBodyComponent::GetOrientation() const noexcept + { + SHQuaternion result; + + if (rigidBody) + { + const auto RP3D_RESULT = rigidBody->getTransform().getOrientation(); + result = SHQuaternion{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z, RP3D_RESULT.w }; + } + + return result; + } + + /*-----------------------------------------------------------------------------------*/ + /* Setter Function Definitions */ + /*-----------------------------------------------------------------------------------*/ + + void SHRigidBodyComponent::SetType(Type newType) noexcept + { + if (type == newType) + return; + + type = newType; + if (rigidBody) + rigidBody->setType(static_cast(newType)); + } + + void SHRigidBodyComponent::SetMass(float newMass) noexcept + { + mass = newMass; + if (rigidBody) + rigidBody->setMass(newMass); + } + + void SHRigidBodyComponent::SetDrag(float newDrag) noexcept + { + drag = newDrag; + if (rigidBody) + rigidBody->setLinearDamping(newDrag); + } + + void SHRigidBodyComponent::SetAngularDrag(float newAngularDrag) noexcept + { + angularDrag = newAngularDrag; + if (rigidBody) + rigidBody->setAngularDamping(newAngularDrag); + } + + void SHRigidBodyComponent::SetGravityEnabled(bool enableGravity) noexcept + { + SetFlag(enableGravity, 0); + if (rigidBody) + rigidBody->enableGravity(enableGravity); + } + + void SHRigidBodyComponent::SetSleepingEnabled(bool enableSleeping) noexcept + { + SetFlag(enableSleeping, 1); + if (rigidBody) + rigidBody->setIsAllowedToSleep(enableSleeping); + } + + void SHRigidBodyComponent::SetFreezePositionX(bool freezePositionX) noexcept + { + SetFlag(freezePositionX, 2); + SetRP3DLinearConstraints(); + } + + void SHRigidBodyComponent::SetFreezePositionY(bool freezePositionY) noexcept + { + SetFlag(freezePositionY, 3); + SetRP3DLinearConstraints(); + } + + void SHRigidBodyComponent::SetFreezePositionZ(bool freezePositionZ) noexcept + { + SetFlag(freezePositionZ, 4); + SetRP3DLinearConstraints(); + } + + void SHRigidBodyComponent::SetFreezeRotationX(bool freezeRotationX) noexcept + { + SetFlag(freezeRotationX, 5); + SetRP3DAngularConstraints(); + } + + void SHRigidBodyComponent::SetFreezeRotationY(bool freezeRotationY) noexcept + { + SetFlag(freezeRotationY, 6); + SetRP3DAngularConstraints(); + } + + void SHRigidBodyComponent::SetFreezeRotationZ(bool freezeRotationZ) noexcept + { + SetFlag(freezeRotationZ, 7); + SetRP3DAngularConstraints(); + } + + void SHRigidBodyComponent::SetLinearVelocity(const SHVec3& newLinearVelocity) const noexcept + { + if (rigidBody) + { + const rp3d::Vector3 NEW_V { newLinearVelocity.x, newLinearVelocity.y, newLinearVelocity.z }; + rigidBody->setLinearVelocity(NEW_V); + } + } + + void SHRigidBodyComponent::SetAngularVelocity(const SHVec3& newAngularVelocity) const noexcept + { + if (rigidBody) + { + const rp3d::Vector3 NEW_V { newAngularVelocity.x, newAngularVelocity.y, newAngularVelocity.z }; + rigidBody->setAngularVelocity(NEW_V); + } + } + + /*-----------------------------------------------------------------------------------*/ + /* Public Function Member Definitions */ + /*-----------------------------------------------------------------------------------*/ + + void SHRigidBodyComponent::AddForce(const SHVec3& force) const noexcept + { + if (rigidBody) + { + const rp3d::Vector3 F { force.x, force.y, force.z }; + rigidBody->applyWorldForceAtCenterOfMass(F); + } + } + + void SHRigidBodyComponent::AddForceAtLocalPos(const SHVec3& force, const SHVec3& localPos) const noexcept + { + if (rigidBody) + { + const rp3d::Vector3 F{ force.x, force.y, force.z }; + const rp3d::Vector3 P{ localPos.x, localPos.y, localPos.z }; + rigidBody->applyWorldForceAtLocalPosition(F, P); + } + } + + void SHRigidBodyComponent::AddForceAtWorldPos(const SHVec3& force, const SHVec3& worldPos) const noexcept + { + if (rigidBody) + { + const rp3d::Vector3 F{ force.x, force.y, force.z }; + const rp3d::Vector3 P{ worldPos.x, worldPos.y, worldPos.z }; + rigidBody->applyWorldForceAtWorldPosition(F, P); + } + } + + void SHRigidBodyComponent::AddRelativeForce(const SHVec3& relativeForce) const noexcept + { + if (rigidBody) + { + const rp3d::Vector3 F{ relativeForce.x, relativeForce.y, relativeForce.z }; + rigidBody->applyLocalForceAtCenterOfMass(F); + } + } + + void SHRigidBodyComponent::AddRelativeForceAtLocalPos(const SHVec3& relativeForce, const SHVec3& localPos) const noexcept + { + if (rigidBody) + { + const rp3d::Vector3 F{ relativeForce.x, relativeForce.y, relativeForce.z }; + const rp3d::Vector3 P{ localPos.x, localPos.y, localPos.z }; + rigidBody->applyLocalForceAtLocalPosition(F, P); + } + } + + void SHRigidBodyComponent::AddRelativeForceAtWorldPos(const SHVec3& relativeForce, const SHVec3& worldPos) const noexcept + { + if (rigidBody) + { + const rp3d::Vector3 F{ relativeForce.x, relativeForce.y, relativeForce.z }; + const rp3d::Vector3 P{ worldPos.x, worldPos.y, worldPos.z }; + rigidBody->applyLocalForceAtWorldPosition(F, P); + } + } + + void SHRigidBodyComponent::AddTorque(const SHVec3& torque) const noexcept + { + if (rigidBody) + { + const rp3d::Vector3 T{ torque.x, torque.y, torque.z }; + rigidBody->applyWorldTorque(T); + } + } + + void SHRigidBodyComponent::AddRelativeTorque(const SHVec3& relativeTorque) const noexcept + { + if (rigidBody) + { + const rp3d::Vector3 T{ relativeTorque.x, relativeTorque.y, relativeTorque.z }; + rigidBody->applyLocalTorque(T); + } + } + + /*-----------------------------------------------------------------------------------*/ + /* Private Function Member Definitions */ + /*-----------------------------------------------------------------------------------*/ + + void SHRigidBodyComponent::SetFlag(bool flagState, int flagPos) + { + flagState ? flags |= (1U << flagPos) : flags &= ~(1U << flagPos); + } + + void SHRigidBodyComponent::SetRP3DLinearConstraints() const + { + const rp3d::Vector3 CONSTRAINTS + { + flags & 1U << 2 ? 1.0f : 0.0f, + flags & 1U << 3 ? 1.0f : 0.0f, + flags & 1U << 4 ? 1.0f : 0.0f + }; + + if (rigidBody) + rigidBody->setLinearLockAxisFactor(CONSTRAINTS); + } + + void SHRigidBodyComponent::SetRP3DAngularConstraints() const + { + const rp3d::Vector3 CONSTRAINTS + { + flags & 1U << 5 ? 1.0f : 0.0f, + flags & 1U << 6 ? 1.0f : 0.0f, + flags & 1U << 7 ? 1.0f : 0.0f + }; + + if (rigidBody) + rigidBody->setAngularLockAxisFactor(CONSTRAINTS); + } + +} // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h new file mode 100644 index 00000000..69338b1e --- /dev/null +++ b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h @@ -0,0 +1,147 @@ +/**************************************************************************************** + * \file SHRigidBodyComponent.h + * \author Diren D Bharwani, diren.dbharwani, 390002520 + * \brief Interface for a Rigidbody Component. + * + * \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 + +// Project Headers +#include "Math/Vector/SHVec3.h" +#include "Math/SHMatrix.h" +#include "ECS_Base/Components/SHComponent.h" + +namespace SHADE +{ + class SH_API SHRigidBodyComponent : public SHComponent + { + public: + /*---------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*---------------------------------------------------------------------------------*/ + + enum class Type + { + STATIC + , KINEMATIC + , DYNAMIC + + , COUNT + }; + + // TODO(Diren): Collision Types + + /*---------------------------------------------------------------------------------*/ + /* Constructors & Destructor */ + /*---------------------------------------------------------------------------------*/ + + SHRigidBodyComponent () noexcept; + SHRigidBodyComponent (const SHRigidBodyComponent& rhs) noexcept = default; + SHRigidBodyComponent (SHRigidBodyComponent&& rhs) noexcept = default; + ~SHRigidBodyComponent () override; + + /*---------------------------------------------------------------------------------*/ + /* Operator Overloads */ + /*---------------------------------------------------------------------------------*/ + + SHRigidBodyComponent& operator=(const SHRigidBodyComponent& rhs) noexcept = default; + SHRigidBodyComponent& operator=(SHRigidBodyComponent&& rhs) noexcept = default; + + /*---------------------------------------------------------------------------------*/ + /* Getter Functions */ + /*---------------------------------------------------------------------------------*/ + + [[nodiscard]] bool IsGravityEnabled () const noexcept; + [[nodiscard]] bool IsSleepingEnabled () const noexcept; + + [[nodiscard]] Type GetType () const noexcept; + [[nodiscard]] float GetMass () const noexcept; + [[nodiscard]] float GetDrag () const noexcept; + [[nodiscard]] float GetAngularDrag () const noexcept; + + [[nodiscard]] bool GetFreezePositionX () const noexcept; + [[nodiscard]] bool GetFreezePositionY () const noexcept; + [[nodiscard]] bool GetFreezePositionZ () const noexcept; + + [[nodiscard]] bool GetFreezeRotationX () const noexcept; + [[nodiscard]] bool GetFreezeRotationY () const noexcept; + [[nodiscard]] bool GetFreezeRotationZ () const noexcept; + + [[nodiscard]] SHVec3 GetForce () const noexcept; + [[nodiscard]] SHVec3 GetTorque () const noexcept; + [[nodiscard]] SHVec3 GetLinearVelocity () const noexcept; + [[nodiscard]] SHVec3 GetAngularVelocity () const noexcept; + [[nodiscard]] SHVec3 GetPosition () const noexcept; + [[nodiscard]] SHQuaternion GetOrientation () const noexcept; + + /*---------------------------------------------------------------------------------*/ + /* Setter Functions */ + /*---------------------------------------------------------------------------------*/ + + void SetType (Type newType) noexcept; + void SetMass (float newMass) noexcept; + void SetDrag (float newDrag) noexcept; + void SetAngularDrag (float newAngularDrag) noexcept; + + void SetGravityEnabled (bool enableGravity) noexcept; + void SetSleepingEnabled (bool enableSleeping) noexcept; + void SetFreezePositionX (bool freezePositionX) noexcept; + void SetFreezePositionY (bool freezePositionY) noexcept; + void SetFreezePositionZ (bool freezePositionZ) noexcept; + void SetFreezeRotationX (bool freezeRotationX) noexcept; + void SetFreezeRotationY (bool freezeRotationY) noexcept; + void SetFreezeRotationZ (bool freezeRotationZ) noexcept; + + void SetLinearVelocity (const SHVec3& newLinearVelocity) const noexcept; + void SetAngularVelocity (const SHVec3& newAngularVelocity) const noexcept; + + /*---------------------------------------------------------------------------------*/ + /* Function Members */ + /*---------------------------------------------------------------------------------*/ + + void AddForce (const SHVec3& force) const noexcept; + void AddForceAtLocalPos (const SHVec3& force, const SHVec3& localPos) const noexcept; + void AddForceAtWorldPos (const SHVec3& force, const SHVec3& worldPos) const noexcept; + + void AddRelativeForce (const SHVec3& relativeForce) const noexcept; + void AddRelativeForceAtLocalPos (const SHVec3& relativeForce, const SHVec3& localPos) const noexcept; + void AddRelativeForceAtWorldPos (const SHVec3& relativeForce, const SHVec3& worldPos) const noexcept; + + void AddTorque (const SHVec3& torque) const noexcept; + void AddRelativeTorque (const SHVec3& relativeTorque) const noexcept; + + private: + /*---------------------------------------------------------------------------------*/ + /* Data Members */ + /*---------------------------------------------------------------------------------*/ + + rp3d::RigidBody* rigidBody; + + Type type; + + float mass; + float drag; + float angularDrag; + + SHMatrix inertiaTensor; + + // rX rY rZ pX pY pZ slp g + uint8_t flags; + + /*---------------------------------------------------------------------------------*/ + /* Function Members */ + /*---------------------------------------------------------------------------------*/ + + void SetFlag (bool flagState, int flagPos); + void SetRP3DLinearConstraints () const ; + void SetRP3DAngularConstraints () const ; + + + }; +} // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/SHpch.h b/SHADE_Engine/src/SHpch.h index 8b2f11f3..7e308829 100644 --- a/SHADE_Engine/src/SHpch.h +++ b/SHADE_Engine/src/SHpch.h @@ -38,3 +38,4 @@ #include "Common/SHCommonTypes.h" #include "Tools/SHLogger.h" +#include "Tools/SHException.h" diff --git a/SHADE_Engine/src/Tools/SHException.h b/SHADE_Engine/src/Tools/SHException.h index 251217eb..2e0b82a9 100644 --- a/SHADE_Engine/src/Tools/SHException.h +++ b/SHADE_Engine/src/Tools/SHException.h @@ -75,10 +75,13 @@ namespace SHADE }; } -#define SHASSERT(cond, msg) \ - if (!(cond)) \ - { \ - SHLOGV_CRITICAL(msg) \ - std::abort(); \ - } - +#ifdef _DEBUG + #define SHASSERT(cond, msg) \ + if (!(cond)) \ + { \ + SHLOGV_CRITICAL(msg) \ + std::abort(); \ + } +#else + #define SHASSERT(cond, msg) { } +#endif From a08b12381457c3f26910926f1ab1ab471fdf05e4 Mon Sep 17 00:00:00 2001 From: Diren D Bharwani Date: Wed, 28 Sep 2022 13:34:35 +0800 Subject: [PATCH 02/17] Added reactphysics to SHADE_Application premake file --- SHADE_Application/premake5.lua | 3 +- .../src/Application/SBApplication.cpp | 31 +++++++++++++------ 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/SHADE_Application/premake5.lua b/SHADE_Application/premake5.lua index b34b06fa..27910231 100644 --- a/SHADE_Application/premake5.lua +++ b/SHADE_Application/premake5.lua @@ -35,7 +35,8 @@ project "SHADE_Application" "%{IncludeDir.VMA}/include", "%{IncludeDir.VULKAN}/Source/SPIRV-Reflect", "%{IncludeDir.RTTR}/include", - "%{IncludeDir.tinyddsloader}" + "%{IncludeDir.tinyddsloader}", + "%{IncludeDir.reactphysics3d}\\include" } externalwarnings "Off" diff --git a/SHADE_Application/src/Application/SBApplication.cpp b/SHADE_Application/src/Application/SBApplication.cpp index 20aa3b5a..82ca0f1c 100644 --- a/SHADE_Application/src/Application/SBApplication.cpp +++ b/SHADE_Application/src/Application/SBApplication.cpp @@ -17,16 +17,25 @@ #define SDL_HINT_VIDEO_FOREIGN_WINDOW_VULKAN 1 #include -#include "Scripting/SHScriptEngine.h" + #include "Graphics/MiddleEnd/Meshes/SHPrimitiveGenerator.h" + +// Managers #include "ECS_Base/Managers/SHEntityManager.h" -#include "Graphics/MiddleEnd/Interface/SHRenderable.h" #include "Scene/SHSceneManager.h" -#include "Math/Transform/SHTransformSystem.h" + +// Systems #include "Input/SHInputManagerSystem.h" +#include "Scripting/SHScriptEngine.h" +#include "Physics/SHPhysicsSystem.h" +#include "Math/Transform/SHTransformSystem.h" + +// Components +#include "Graphics/MiddleEnd/Interface/SHRenderable.h" +#include "Math/Transform/SHTransformComponent.h" #include "Scenes/SBTestScene.h" -#include "Math/Transform/SHTransformComponent.h" + #include "Assets/SHAssetManager.h" @@ -51,31 +60,33 @@ namespace Sandbox // Create Systems SHADE::SHSystemManager::CreateSystem(); SHADE::SHSystemManager::CreateSystem(); - // TODO(Diren): Create Physics System here + SHADE::SHSystemManager::CreateSystem(); SHADE::SHSystemManager::CreateSystem(); SHADE::SHGraphicsSystem* graphicsSystem = static_cast(SHADE::SHSystemManager::GetSystem()); SHADE::SHSystemManager::CreateSystem(); // Create Routines + SHADE::SHSystemManager::RegisterRoutine(); + SHADE::SHSystemManager::RegisterRoutine(); SHADE::SHSystemManager::RegisterRoutine(); SHADE::SHSystemManager::RegisterRoutine(); SHADE::SHSystemManager::RegisterRoutine(); - // TODO(Diren): Register Physics System & Routines here + SHADE::SHSystemManager::RegisterRoutine(); + SHADE::SHSystemManager::RegisterRoutine(); + SHADE::SHSystemManager::RegisterRoutine(); SHADE::SHSystemManager::RegisterRoutine(); - SHADE::SHComponentManager::CreateComponentSparseSet(); SHADE::SHSystemManager::RegisterRoutine(); SHADE::SHSystemManager::RegisterRoutine(); SHADE::SHSystemManager::RegisterRoutine(); SHADE::SHSystemManager::RegisterRoutine(); - SHADE::SHComponentManager::CreateComponentSparseSet(); SHADE::SHComponentManager::CreateComponentSparseSet(); - - SHADE::SHSystemManager::RegisterRoutine(); + SHADE::SHComponentManager::CreateComponentSparseSet(); + SHADE::SHComponentManager::CreateComponentSparseSet(); //TODO: REMOVE AFTER PRESENTATION SHADE::SHAssetManager::LoadDataTemp("../../Assets/racoon.gltf"); From 097b1be3f7e23924fc5f562cf0ee802491aca171 Mon Sep 17 00:00:00 2001 From: Diren D Bharwani Date: Wed, 28 Sep 2022 16:15:36 +0800 Subject: [PATCH 03/17] Added Physics System --- .../src/Application/SBApplication.cpp | 1 - .../ECS_Base/System/SHFixedSystemRoutine.h | 16 +- .../Components/SHRigidBodyComponent.cpp | 15 + .../Physics/Components/SHRigidBodyComponent.h | 10 +- SHADE_Engine/src/Physics/SHPhysicsSystem.cpp | 446 ++++++++++++++++++ SHADE_Engine/src/Physics/SHPhysicsSystem.h | 237 ++++++++++ 6 files changed, 712 insertions(+), 13 deletions(-) create mode 100644 SHADE_Engine/src/Physics/SHPhysicsSystem.cpp create mode 100644 SHADE_Engine/src/Physics/SHPhysicsSystem.h diff --git a/SHADE_Application/src/Application/SBApplication.cpp b/SHADE_Application/src/Application/SBApplication.cpp index 82ca0f1c..fdc933b9 100644 --- a/SHADE_Application/src/Application/SBApplication.cpp +++ b/SHADE_Application/src/Application/SBApplication.cpp @@ -86,7 +86,6 @@ namespace Sandbox SHADE::SHComponentManager::CreateComponentSparseSet(); SHADE::SHComponentManager::CreateComponentSparseSet(); - SHADE::SHComponentManager::CreateComponentSparseSet(); //TODO: REMOVE AFTER PRESENTATION SHADE::SHAssetManager::LoadDataTemp("../../Assets/racoon.gltf"); diff --git a/SHADE_Engine/src/ECS_Base/System/SHFixedSystemRoutine.h b/SHADE_Engine/src/ECS_Base/System/SHFixedSystemRoutine.h index d9a2b510..d54d9441 100644 --- a/SHADE_Engine/src/ECS_Base/System/SHFixedSystemRoutine.h +++ b/SHADE_Engine/src/ECS_Base/System/SHFixedSystemRoutine.h @@ -8,23 +8,19 @@ namespace SHADE { class SHFixedSystemRoutine: public SHSystemRoutine { - private: - double accumulatedTime; - double fixedTimeStep; - protected: - SHFixedSystemRoutine(double timeStep = DEFAULT_FIXED_STEP, std::string routineName = "Default Fixed Routine Name", bool editorPause = false) + double accumulatedTime; + double fixedTimeStep; + + SHFixedSystemRoutine(double timeStep = DEFAULT_FIXED_STEP, std::string routineName = "Default Fixed Routine Name", bool editorPause = false) :SHSystemRoutine(routineName, editorPause), accumulatedTime(0.0), fixedTimeStep(timeStep){} - - public: ~SHFixedSystemRoutine() = default; - virtual void Execute(double dt) noexcept; - - virtual void FixedExecute(double dt) noexcept {}; + virtual void Execute(double dt) noexcept override; + virtual void FixedExecute(double dt) noexcept {} }; diff --git a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp index 2de6e52a..e3989d6e 100644 --- a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp +++ b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp @@ -465,6 +465,21 @@ namespace SHADE /* Private Function Member Definitions */ /*-----------------------------------------------------------------------------------*/ + void SHRigidBodyComponent::SyncRP3DAndSHADE() + { + rigidBody->setType(static_cast(type)); + + rigidBody->setMass(mass); + rigidBody->setLinearDamping(drag); + rigidBody->setAngularDamping(angularDrag); + + rigidBody->enableGravity(flags & (1U << 0)); + rigidBody->setIsAllowedToSleep(flags & (1U << 1)); + SetRP3DLinearConstraints(); + SetRP3DAngularConstraints(); + } + + void SHRigidBodyComponent::SetFlag(bool flagState, int flagPos) { flagState ? flags |= (1U << flagPos) : flags &= ~(1U << flagPos); diff --git a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h index 69338b1e..668ab6bd 100644 --- a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h +++ b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h @@ -21,6 +21,13 @@ namespace SHADE { class SH_API SHRigidBodyComponent : public SHComponent { + private: + /*---------------------------------------------------------------------------------*/ + /* Friends */ + /*---------------------------------------------------------------------------------*/ + + friend class SHPhysicsSystem; + public: /*---------------------------------------------------------------------------------*/ /* Type Definitions */ @@ -128,8 +135,6 @@ namespace SHADE float mass; float drag; float angularDrag; - - SHMatrix inertiaTensor; // rX rY rZ pX pY pZ slp g uint8_t flags; @@ -138,6 +143,7 @@ namespace SHADE /* Function Members */ /*---------------------------------------------------------------------------------*/ + void SyncRP3DAndSHADE (); void SetFlag (bool flagState, int flagPos); void SetRP3DLinearConstraints () const ; void SetRP3DAngularConstraints () const ; diff --git a/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp b/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp new file mode 100644 index 00000000..537c2c70 --- /dev/null +++ b/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp @@ -0,0 +1,446 @@ +/**************************************************************************************** + * \file SHPhysicsSystem.cpp + * \author Diren D Bharwani, diren.dbharwani, 390002520 + * \brief Implementation for the Physics System + * + * \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 + +// Primary Header +#include "SHPhysicsSystem.h" + +// Project Headers +#include "Math/Transform/SHTransformComponent.h" +#include "Scene/SHSceneManager.h" +#include "ECS_Base/Managers/SHComponentManager.h" +#include "ECS_Base/Managers/SHEntityManager.h" +#include "Graphics/MiddleEnd/Interface/SHRenderable.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Constructors & Destructor Definitions */ + /*-----------------------------------------------------------------------------------*/ + + SHPhysicsSystem::PhysicsPreUpdate::PhysicsPreUpdate() + : SHSystemRoutine { "Physics PreUpdate", true } + {} + + SHPhysicsSystem::PhysicsFixedUpdate::PhysicsFixedUpdate() + : SHFixedSystemRoutine { DEFAULT_FIXED_STEP, "Physics FixedUpdate", true } + {} + + SHPhysicsSystem::PhysicsPostUpdate::PhysicsPostUpdate() + : SHSystemRoutine { "Physics PostUpdate", true } + {} + + /*-----------------------------------------------------------------------------------*/ + /* Getter Function Definitions */ + /*-----------------------------------------------------------------------------------*/ + + bool SHPhysicsSystem::IsSleepingEnabled() const noexcept + { + if (world) + return world->isSleepingEnabled(); + + SHLOGV_WARNING("No physics world has been initialised!") + return false; + } + + //double SHPhysicsSystem::GetFixedUpdate() const noexcept + //{ + // return fixedUpdate; + //} + + SHVec3 SHPhysicsSystem::GetWorldGravity() const noexcept + { + SHVec3 result; + + if (world) + { + const auto RP3D_GRAVITY = world->getGravity(); + result.x = RP3D_GRAVITY.x; + result.y = RP3D_GRAVITY.y; + result.z = RP3D_GRAVITY.z; + } + else + { + SHLOGV_WARNING("No physics world has been initialised!") + } + + return result; + } + + uint16_t SHPhysicsSystem::GetNumberVelocityIterations() const noexcept + { + if (world) + return world->getNbIterationsVelocitySolver(); + + SHLOGV_WARNING("No physics world has been initialised!") + return 0; + } + + uint16_t SHPhysicsSystem::GetNumberPositionIterations() const noexcept + { + if (world) + return world->getNbIterationsPositionSolver(); + + SHLOGV_WARNING("No physics world has been initialised!") + return 0; + } + + /*-----------------------------------------------------------------------------------*/ + /* Setter Function Definitions */ + /*-----------------------------------------------------------------------------------*/ + + //void SHPhysicsSystem::SetFixedUpdate(double fixedUpdateRate) noexcept + //{ + // fixedUpdate = fixedUpdateRate; + // SHLOG_INFO("Setting Physics update rate to {}", 1.0 / fixedUpdate) + //} + + void SHPhysicsSystem::SetWorldGravity(const SHVec3& gravity) const noexcept + { + if (world) + { + const rp3d::Vector3 G { gravity.x, gravity.y, gravity.z }; + world->setGravity(G); + } + else + { + SHLOGV_WARNING("No physics world has been initialised!") + } + } + + void SHPhysicsSystem::SetNumberVelocityIterations(uint16_t numVelIterations) const noexcept + { + if (world) + { + world->setNbIterationsVelocitySolver(numVelIterations); + } + else + { + SHLOGV_WARNING("No physics world has been initialised!") + } + } + + void SHPhysicsSystem::SetNumberPositionIterations(uint16_t numPosIterations) const noexcept + { + if (world) + { + world->setNbIterationsPositionSolver(numPosIterations); + } + else + { + SHLOGV_WARNING("No physics world has been initialised!") + } + } + + void SHPhysicsSystem::SetSleepingEnabled(bool enableSleeping) const noexcept + { + if (world) + { + world->enableSleeping(enableSleeping); + } + else + { + SHLOGV_WARNING("No physics world has been initialised!") + } + } + + void SHPhysicsSystem::SetWorldSettings(const WorldSettings& settings) const noexcept + { + if (world) + { + const rp3d::Vector3 G { settings.gravity.x, settings.gravity.y, settings.gravity.z }; + world->setGravity(G); + world->setNbIterationsVelocitySolver(settings.numVelocitySolverIterations); + world->setNbIterationsPositionSolver(settings.numPositionSolverIterations); + world->enableSleeping(settings.sleepingEnabled); + } + else + { + SHLOGV_WARNING("No physics world has been initialised!") + } + } + + /*-----------------------------------------------------------------------------------*/ + /* Public Function Member Definitions */ + /*-----------------------------------------------------------------------------------*/ + + void SHPhysicsSystem::Init() + { + using namespace rp3d; + + // Create a physics world with the default settings + PhysicsWorld::WorldSettings settings; + settings.gravity = Vector3{ 0, -9.81, 0 }; + settings.isSleepingEnabled = true; + settings.defaultVelocitySolverNbIterations = 8; + settings.defaultPositionSolverNbIterations = 3; + + world = factory.createPhysicsWorld(settings); + + // Create component sparse sets + SHADE::SHComponentManager::CreateComponentSparseSet(); + } + + void SHPhysicsSystem::Exit() + { + factory.destroyPhysicsWorld(world); + } + + void SHPhysicsSystem::AddRigidBodyComponent(EntityID id) noexcept + { + const UpdateCommand NEW_CMD + { + .component = UpdateComponent::RIGID_BODY, + .type = UpdateType::ADD, + .entityID = id + }; + + updateQueue.push(NEW_CMD); + } + + void SHPhysicsSystem::AddColliderComponent(EntityID id) noexcept + { + const UpdateCommand NEW_CMD + { + .component = UpdateComponent::COLLIDER, + .type = UpdateType::ADD, + .entityID = id + }; + + updateQueue.push(NEW_CMD); + } + + void SHPhysicsSystem::RemoveRigidBodyComponent(EntityID id) noexcept + { + const UpdateCommand NEW_CMD + { + .component = UpdateComponent::RIGID_BODY, + .type = UpdateType::REMOVE, + .entityID = id + }; + + updateQueue.push(NEW_CMD); + } + + void SHPhysicsSystem::RemoveColliderComponent(EntityID id) noexcept + { + const UpdateCommand NEW_CMD + { + .component = UpdateComponent::COLLIDER, + .type = UpdateType::REMOVE, + .entityID = id + }; + + updateQueue.push(NEW_CMD); + } + + void SHPhysicsSystem::PhysicsPreUpdate::Execute([[maybe_unused]]double dt) noexcept + { + auto* system = reinterpret_cast(GetSystem()); + system->ClearUpdateQueue(); + + // Sync active states: if node or component is not active, set rp3d to inactive + static const auto SYNC_ACTIVE = [](SHSceneNode* node) + { + const EntityID ENTITY_ID = node->GetEntityID(); + + // Check if has rigid body + auto const* rigidBodyComponent = SHComponentManager::GetComponent_s(ENTITY_ID); + if(rigidBodyComponent) + { + const bool RP3D_ACTIVE = rigidBodyComponent->rigidBody->isActive(); + const bool SHADE_ACTIVE = node->IsActive() && rigidBodyComponent->isActive; + + if (RP3D_ACTIVE != SHADE_ACTIVE) + rigidBodyComponent->rigidBody->setIsActive(SHADE_ACTIVE); + } + else // Check for a collider + { + + } + }; + + const auto& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); + sceneGraph.Traverse(SYNC_ACTIVE); + } + + //void SHPhysicsSystem::PhysicsFixedUpdate::Execute(double dt) noexcept + //{ + // // I had to override this anyway due to needing to calculate the + // // interpolation factor right after the fixed update was done + + // auto* system = reinterpret_cast(GetSystem()); + // fixedTimeStep = 1.0 / system->fixedUpdate; + + // accumulatedTime += dt; + // int counter = 0; + + // while (accumulatedTime > fixedTimeStep) + // { + // FixedExecute(fixedTimeStep); + + // accumulatedTime -= fixedTimeStep; + // ++counter; + // } + + // stats.numSteps = counter; + + // system->interpolationFactor = accumulatedTime / fixedTimeStep; + //} + + void SHPhysicsSystem::PhysicsFixedUpdate::FixedExecute(double dt) noexcept + { + auto* system = reinterpret_cast(GetSystem()); + system->world->update(static_cast(dt)); + + system->fixedDT = fixedTimeStep; + system->accumulatedTime = accumulatedTime; + } + + void SHPhysicsSystem::PhysicsPostUpdate::Execute(double dt) noexcept + { + // Interpolate transforms for rendering + const auto& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); + sceneGraph.Traverse([](SHSceneNode* node) + { + const EntityID ENTITY_ID = node->GetEntityID(); + + // Check if has rigid body + if (auto* rb = SHComponentManager::GetComponent_s(ENTITY_ID); rb) + { + // TODO(Diren): Interpolate transforms for rendering + if (node->IsActive() && rb->isActive) + { + // Get SHADE transform + auto* transformComponent = SHComponentManager::GetComponent_s(ENTITY_ID); + SHASSERT(transformComponent != nullptr, "Transform Component missing from Entity " + std::to_string(ENTITY_ID)) + + const auto& RP3D_POS = rb->GetPosition(); + const SHVec3 SHADE_POS{ RP3D_POS.x, RP3D_POS.y, RP3D_POS.z }; + + const auto& SHADE_ROT = rb->GetOrientation().ToEuler(); + + transformComponent->SetWorldPosition(SHADE_POS); + transformComponent->SetWorldRotation(SHADE_ROT); + } + else // Check for a collider + { + + } + } + }); + + // TODO(Diren): Handle trigger messages for scripting + } + + /*-----------------------------------------------------------------------------------*/ + /* Private Function Member Definitions */ + /*-----------------------------------------------------------------------------------*/ + + void SHPhysicsSystem::ClearUpdateQueue() noexcept + { + while (!updateQueue.empty()) + { + const auto& CMD = updateQueue.front(); + switch (CMD.type) + { + case UpdateType::ADD: + { + switch (CMD.component) + { + case UpdateComponent::RIGID_BODY: AddRigidBody(CMD.entityID); break; + //case UpdateComponent::COLLIDER: AddCollider(CMD.entityID); break; + default: break; + } + } + case UpdateType::REMOVE: + { + switch (CMD.component) + { + case UpdateComponent::RIGID_BODY: RemoveRigidBody(CMD.entityID); break; + //case UpdateComponent::COLLIDER: RemoveCollider(CMD.entityID); break; + default: break; + } + } + default: break; + } + + updateQueue.pop(); + } + } + + + void SHPhysicsSystem::AddRigidBody(EntityID entityID) const noexcept + { + #ifdef _DEBUG + SHLOG_INFO("Adding a Rigidbody to the Physics World.") + #endif + + // Rigid Bodies need a transform. + auto const* transformComponent = SHComponentManager::GetComponent_s(entityID); + if (!transformComponent) + { + // NOTE: This should already be handled by the editor. + + SHLOG_INFO("Automatically adding a transform to Entity {}", entityID) + SHComponentManager::AddComponent(entityID); + transformComponent = SHComponentManager::GetComponent(entityID); + } + + const SHVec3& SHADE_WORLD_POSITION = transformComponent->GetWorldPosition(); + const rp3d::Vector3 RP3D_POSITION { SHADE_WORLD_POSITION.x, SHADE_WORLD_POSITION.y, SHADE_WORLD_POSITION.z }; + + const SHVec3& SHADE_WORLD_ROTATION = transformComponent->GetWorldRotation(); + const rp3d::Quaternion RP3D_ORIENTATION = rp3d::Quaternion::fromEulerAngles(SHADE_WORLD_ROTATION.x, SHADE_WORLD_ROTATION.y, SHADE_WORLD_ROTATION.z); + + const rp3d::Transform RP3D_TF { RP3D_POSITION, RP3D_ORIENTATION }; + + auto* rigidBodyComponent = SHComponentManager::GetComponent_s(entityID); + if (!rigidBodyComponent) + { + // NOTE: This should already be handled by the editor. + + SHLOG_INFO("Automatically adding a rigidbody to Entity {}", entityID) + SHComponentManager::AddComponent(entityID); + rigidBodyComponent = SHComponentManager::GetComponent(entityID); + } + + rigidBodyComponent->rigidBody = world->createRigidBody(RP3D_TF); + rigidBodyComponent->SyncRP3DAndSHADE(); + + // Reassign collider + //if (collider) + //{ + // collider. + //} + } + + void SHPhysicsSystem::RemoveRigidBody(EntityID entityID) const noexcept + { + #ifdef _DEBUG + SHLOG_INFO("Removing a Rigidbody from the Physics World.") + #endif + + auto* rigidBodyComponent = SHComponentManager::GetComponent_s(entityID); + if (rigidBodyComponent == nullptr) + { + SHLOG_ERROR("Entity {} does not have a rigidbody component to remove!", entityID) + return; + } + + // If a collider exists, remake the colliders with a collision body + + world->destroyRigidBody(rigidBodyComponent->rigidBody); + rigidBodyComponent->rigidBody = nullptr; // this should be redundant + } + + +} // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHPhysicsSystem.h b/SHADE_Engine/src/Physics/SHPhysicsSystem.h new file mode 100644 index 00000000..dac6836a --- /dev/null +++ b/SHADE_Engine/src/Physics/SHPhysicsSystem.h @@ -0,0 +1,237 @@ +/**************************************************************************************** + * \file SHPhysicsSystem.h + * \author Diren D Bharwani, diren.dbharwani, 390002520 + * \brief Interface for the Physics System + * + * \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 +#include + +#include + +// Project Headers +#include "Math/SHQuaternion.h" +#include "Components/SHRigidBodyComponent.h" + +#include "Scene/SHSceneGraph.h" +#include "ECS_Base/System/SHSystemRoutine.h" +#include "ECS_Base/System/SHFixedSystemRoutine.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*-----------------------------------------------------------------------------------*/ + + class SH_API SHPhysicsSystem : public SHSystem + { + public: + /*---------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*---------------------------------------------------------------------------------*/ + + struct WorldSettings + { + SHVec3 gravity; + uint16_t numVelocitySolverIterations; + uint16_t numPositionSolverIterations; + bool sleepingEnabled; + }; + + /*---------------------------------------------------------------------------------*/ + /* Constructors & Destructor */ + /*---------------------------------------------------------------------------------*/ + + SHPhysicsSystem () = default; + ~SHPhysicsSystem () override = default; + + SHPhysicsSystem (const SHPhysicsSystem&) = delete; + SHPhysicsSystem (SHPhysicsSystem&&) = delete; + + /*---------------------------------------------------------------------------------*/ + /* Operator Overloads */ + /*---------------------------------------------------------------------------------*/ + + SHPhysicsSystem& operator= (const SHPhysicsSystem&) = delete; + SHPhysicsSystem& operator= (SHPhysicsSystem&&) = delete; + + /*---------------------------------------------------------------------------------*/ + /* Getter Functions */ + /*---------------------------------------------------------------------------------*/ + + [[nodiscard]] bool IsSleepingEnabled () const noexcept; + + //[[nodiscard]] double GetFixedUpdate () const noexcept; + [[nodiscard]] SHVec3 GetWorldGravity () const noexcept; + [[nodiscard]] uint16_t GetNumberVelocityIterations () const noexcept; + [[nodiscard]] uint16_t GetNumberPositionIterations () const noexcept; + + + /*---------------------------------------------------------------------------------*/ + /* Setter Functions */ + /*---------------------------------------------------------------------------------*/ + + //void SetFixedUpdate (double fixedUpdateRate) noexcept; + void SetWorldGravity (const SHVec3& gravity) const noexcept; + void SetNumberVelocityIterations (uint16_t numVelIterations) const noexcept; + void SetNumberPositionIterations (uint16_t numPosIterations) const noexcept; + void SetSleepingEnabled (bool enableSleeping) const noexcept; + + void SetWorldSettings (const WorldSettings& settings) const noexcept; + + /*---------------------------------------------------------------------------------*/ + /* Function Members */ + /*---------------------------------------------------------------------------------*/ + + void Init () override; + void Exit () override; + + void AddRigidBodyComponent (EntityID id) noexcept; + void AddColliderComponent (EntityID id) noexcept; + void RemoveRigidBodyComponent (EntityID id) noexcept; + void RemoveColliderComponent (EntityID id) noexcept; + + /*---------------------------------------------------------------------------------*/ + /* System Routines */ + /*---------------------------------------------------------------------------------*/ + + class SH_API PhysicsPreUpdate : public SHSystemRoutine + { + public: + /*-------------------------------------------------------------------------------*/ + /* Constructors & Destructor */ + /*-------------------------------------------------------------------------------*/ + + PhysicsPreUpdate(); + ~PhysicsPreUpdate() = default; + + PhysicsPreUpdate(const PhysicsPreUpdate&) = delete; + PhysicsPreUpdate(PhysicsPreUpdate&&) = delete; + + /*-------------------------------------------------------------------------------*/ + /* Operator Overloads */ + /*-------------------------------------------------------------------------------*/ + + PhysicsPreUpdate& operator= (const PhysicsPreUpdate&) = delete; + PhysicsPreUpdate& operator= (PhysicsPreUpdate&&) = delete; + + /*-------------------------------------------------------------------------------*/ + /* Function Members */ + /*-------------------------------------------------------------------------------*/ + + void Execute(double dt) noexcept override; + }; + + class SH_API PhysicsFixedUpdate : public SHFixedSystemRoutine + { + public: + /*-------------------------------------------------------------------------------*/ + /* Constructors & Destructor */ + /*-------------------------------------------------------------------------------*/ + + PhysicsFixedUpdate(); + ~PhysicsFixedUpdate() = default; + + PhysicsFixedUpdate(const PhysicsFixedUpdate&) = delete; + PhysicsFixedUpdate(PhysicsFixedUpdate&&) = delete; + + /*-------------------------------------------------------------------------------*/ + /* Operator Overloads */ + /*-------------------------------------------------------------------------------*/ + + PhysicsFixedUpdate& operator= (const PhysicsFixedUpdate&) = delete; + PhysicsFixedUpdate& operator= (PhysicsFixedUpdate&&) = delete; + + /*-------------------------------------------------------------------------------*/ + /* Function Members */ + /*-------------------------------------------------------------------------------*/ + + //void Execute (double dt) noexcept override; + void FixedExecute (double dt) noexcept override; + }; + + class SH_API PhysicsPostUpdate : public SHSystemRoutine + { + public: + /*-------------------------------------------------------------------------------*/ + /* Constructors & Destructor */ + /*-------------------------------------------------------------------------------*/ + + PhysicsPostUpdate(); + ~PhysicsPostUpdate() = default; + + PhysicsPostUpdate(const PhysicsPostUpdate&) = delete; + PhysicsPostUpdate(PhysicsPostUpdate&&) = delete; + + /*-------------------------------------------------------------------------------*/ + /* Operator Overloads */ + /*-------------------------------------------------------------------------------*/ + + PhysicsPostUpdate& operator= (const PhysicsPostUpdate&) = delete; + PhysicsPostUpdate& operator= (PhysicsPostUpdate&&) = delete; + + /*-------------------------------------------------------------------------------*/ + /* Function Members */ + /*-------------------------------------------------------------------------------*/ + + void Execute(double dt) noexcept override; + }; + + + private: + /*---------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*---------------------------------------------------------------------------------*/ + + enum class UpdateComponent { RIGID_BODY, COLLIDER }; + enum class UpdateType { ADD, REMOVE }; + + struct UpdateCommand + { + UpdateComponent component; + UpdateType type; + EntityID entityID; + }; + + struct CachedTransform + { + SHVec3 position; + SHQuaternion orientation; + }; + + /*---------------------------------------------------------------------------------*/ + /* Data Members */ + /*---------------------------------------------------------------------------------*/ + + //double interpolationFactor; + //double fixedUpdate; + + double accumulatedTime; + double fixedDT; + + rp3d::PhysicsCommon factory; + rp3d::PhysicsWorld* world; + + std::queue updateQueue; + std::unordered_map prevTransforms; // used for interpolation + + /*---------------------------------------------------------------------------------*/ + /* Function Members */ + /*---------------------------------------------------------------------------------*/ + + void ClearUpdateQueue () noexcept; + + void AddRigidBody (EntityID entityID) const noexcept; + void AddCollider (EntityID entityID) const noexcept; + void RemoveRigidBody (EntityID entityID) const noexcept; + void RemoveCollider (EntityID entityID) const noexcept; + }; + + +} // namespace SHADE \ No newline at end of file From 561f2b091f231582896f94c6aca6f74fd3ddcdd4 Mon Sep 17 00:00:00 2001 From: Diren D Bharwani Date: Wed, 28 Sep 2022 21:09:27 +0800 Subject: [PATCH 04/17] Added PhysicsObject to handle interface between components and physics system --- .../Components/SHRigidBodyComponent.cpp | 206 +++++++------- .../Physics/Components/SHRigidBodyComponent.h | 21 +- SHADE_Engine/src/Physics/SHPhysicsObject.cpp | 112 ++++++++ SHADE_Engine/src/Physics/SHPhysicsObject.h | 82 ++++++ SHADE_Engine/src/Physics/SHPhysicsSystem.cpp | 252 ++++++++---------- SHADE_Engine/src/Physics/SHPhysicsSystem.h | 103 +++---- 6 files changed, 446 insertions(+), 330 deletions(-) create mode 100644 SHADE_Engine/src/Physics/SHPhysicsObject.cpp create mode 100644 SHADE_Engine/src/Physics/SHPhysicsObject.h diff --git a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp index e3989d6e..16863dbd 100644 --- a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp +++ b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp @@ -18,12 +18,6 @@ #include "Math/SHMathHelpers.h" #include "Math/SHQuaternion.h" -/*-------------------------------------------------------------------------------------*/ -/* Local Function Definitions */ -/*-------------------------------------------------------------------------------------*/ - - - namespace SHADE { /*-----------------------------------------------------------------------------------*/ @@ -31,8 +25,7 @@ namespace SHADE /*-----------------------------------------------------------------------------------*/ SHRigidBodyComponent::SHRigidBodyComponent() noexcept - : rigidBody { nullptr } - , type { Type::DYNAMIC } + : type { Type::DYNAMIC } , mass { 1.0f } , drag { 0.01f } , angularDrag { 0.01f } @@ -41,13 +34,11 @@ namespace SHADE // Set default flags: Gravity & Sleeping enabled flags |= 1U << 0; flags |= 1U << 1; - - // TODO(Diren): Send an update command to the physics system } SHRigidBodyComponent::~SHRigidBodyComponent() { - rigidBody = nullptr; + } /*-----------------------------------------------------------------------------------*/ @@ -57,9 +48,10 @@ namespace SHADE bool SHRigidBodyComponent::IsGravityEnabled() const noexcept { const bool GRAVITY = flags & (1U << 0); - if (rigidBody) + if (rp3dBody) { - SHASSERT(rigidBody->isGravityEnabled() == GRAVITY, "ReactPhysics and SHADE body enable gravity do not match!") + + SHASSERT(reinterpret_cast(rp3dBody)->isGravityEnabled() == GRAVITY, "ReactPhysics and SHADE body enable gravity do not match!") } return GRAVITY; @@ -68,21 +60,26 @@ namespace SHADE bool SHRigidBodyComponent::IsSleepingEnabled() const noexcept { const bool SLEEP = flags & (1U << 1); - if (rigidBody) + if (rp3dBody) { - SHASSERT(rigidBody->isAllowedToSleep() == SLEEP, "ReactPhysics and SHADE body enable sleep do not match!") + SHASSERT(reinterpret_cast(rp3dBody)->isAllowedToSleep() == SLEEP, "ReactPhysics and SHADE body enable sleep do not match!") } return SLEEP; } + bool SHRigidBodyComponent::IsInterpolating() const noexcept + { + return interpolate; + } + SHRigidBodyComponent::Type SHRigidBodyComponent::GetType() const noexcept { - if (rigidBody) + if (rp3dBody) { SHASSERT ( - SHUtilities::ConvertEnum(rigidBody->getType()) == SHUtilities::ConvertEnum(type), + SHUtilities::ConvertEnum(reinterpret_cast(rp3dBody)->getType()) == SHUtilities::ConvertEnum(type), "ReactPhysics and SHADE body types do not match!" ) } @@ -92,9 +89,9 @@ namespace SHADE float SHRigidBodyComponent::GetMass() const noexcept { - if (rigidBody) + if (rp3dBody) { - SHASSERT(rigidBody->getMass() == mass, "ReactPhysics and SHADE body masses do not match!") + SHASSERT(reinterpret_cast(rp3dBody)->getMass() == mass, "ReactPhysics and SHADE body masses do not match!") } return mass; @@ -102,11 +99,11 @@ namespace SHADE float SHRigidBodyComponent::GetDrag() const noexcept { - if (rigidBody) + if (rp3dBody) { SHASSERT ( - SHMath::CompareFloat(rigidBody->getLinearDamping(), drag), + SHMath::CompareFloat(reinterpret_cast(rp3dBody)->getLinearDamping(), drag), "ReactPhysics and SADE body drag coefficients do not match!" ) } @@ -116,11 +113,11 @@ namespace SHADE float SHRigidBodyComponent::GetAngularDrag() const noexcept { - if (rigidBody) + if (rp3dBody) { SHASSERT ( - SHMath::CompareFloat(rigidBody->getAngularDamping(), angularDrag), + SHMath::CompareFloat(reinterpret_cast(rp3dBody)->getAngularDamping(), angularDrag), "ReactPhysics and SADE body drag coefficients do not match!" ) } @@ -131,9 +128,9 @@ namespace SHADE bool SHRigidBodyComponent::GetFreezePositionX() const noexcept { const bool FREEZE_X_POS = flags & (1U << 2); - if (rigidBody) + if (rp3dBody) { - const bool RP3D_FREEZE_X_POS = fabs(rigidBody->getLinearLockAxisFactor().x) > 0.0f; + const bool RP3D_FREEZE_X_POS = fabs(reinterpret_cast(rp3dBody)->getLinearLockAxisFactor().x) > 0.0f; SHASSERT(RP3D_FREEZE_X_POS == FREEZE_X_POS, "ReactPhysics and SHADE body x-axis position lock do not match!") } @@ -143,9 +140,9 @@ namespace SHADE bool SHRigidBodyComponent::GetFreezePositionY() const noexcept { const bool FREEZE_Y_POS = flags & (1U << 3); - if (rigidBody) + if (rp3dBody) { - const bool RP3D_FREEZE_Y_POS = fabs(rigidBody->getLinearLockAxisFactor().y) > 0.0f; + const bool RP3D_FREEZE_Y_POS = fabs(reinterpret_cast(rp3dBody)->getLinearLockAxisFactor().y) > 0.0f; SHASSERT(RP3D_FREEZE_Y_POS == FREEZE_Y_POS, "ReactPhysics and SHADE body y-axis position lock do not match!") } @@ -155,9 +152,9 @@ namespace SHADE bool SHRigidBodyComponent::GetFreezePositionZ() const noexcept { const bool FREEZE_Z_POS = flags & (1U << 4); - if (rigidBody) + if (rp3dBody) { - const bool RP3D_FREEZE_Z_POS = fabs(rigidBody->getLinearLockAxisFactor().z) > 0.0f; + const bool RP3D_FREEZE_Z_POS = fabs(reinterpret_cast(rp3dBody)->getLinearLockAxisFactor().z) > 0.0f; SHASSERT(RP3D_FREEZE_Z_POS == FREEZE_Z_POS, "ReactPhysics and SHADE body z-axis position lock do not match!") } @@ -167,9 +164,9 @@ namespace SHADE bool SHRigidBodyComponent::GetFreezeRotationX() const noexcept { const bool FREEZE_X_ROT = flags & (1U << 5); - if (rigidBody) + if (rp3dBody) { - const bool RP3D_FREEZE_Y_ROT = fabs(rigidBody->getAngularLockAxisFactor().x) > 0.0f; + const bool RP3D_FREEZE_Y_ROT = fabs(reinterpret_cast(rp3dBody)->getAngularLockAxisFactor().x) > 0.0f; SHASSERT(RP3D_FREEZE_Y_ROT == FREEZE_X_ROT, "ReactPhysics and SHADE body x-axis rotation lock do not match!") } @@ -179,9 +176,9 @@ namespace SHADE bool SHRigidBodyComponent::GetFreezeRotationY() const noexcept { const bool FREEZE_Y_ROT = flags & (1U << 6); - if (rigidBody) + if (rp3dBody) { - const bool RP3D_FREEZE_Y_ROT = fabs(rigidBody->getAngularLockAxisFactor().y) > 0.0f; + const bool RP3D_FREEZE_Y_ROT = fabs(reinterpret_cast(rp3dBody)->getAngularLockAxisFactor().y) > 0.0f; SHASSERT(RP3D_FREEZE_Y_ROT == FREEZE_Y_ROT, "ReactPhysics and SHADE body y-axis rotation lock do not match!") } @@ -191,9 +188,9 @@ namespace SHADE bool SHRigidBodyComponent::GetFreezeRotationZ() const noexcept { const bool FREEZE_Z_ROT = flags & (1U << 7); - if (rigidBody) + if (rp3dBody) { - const bool RP3D_FREEZE_Z_ROT = fabs(rigidBody->getAngularLockAxisFactor().z) > 0.0f; + const bool RP3D_FREEZE_Z_ROT = fabs(reinterpret_cast(rp3dBody)->getAngularLockAxisFactor().z) > 0.0f; SHASSERT(RP3D_FREEZE_Z_ROT == FREEZE_Z_ROT, "ReactPhysics and SHADE body z-axis rotation lock do not match!") } @@ -204,9 +201,9 @@ namespace SHADE { SHVec3 result; - if (rigidBody) + if (rp3dBody) { - const auto RP3D_RESULT = rigidBody->getForce(); + const auto& RP3D_RESULT = reinterpret_cast(rp3dBody)->getForce(); result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z }; } @@ -217,9 +214,9 @@ namespace SHADE { SHVec3 result; - if (rigidBody) + if (rp3dBody) { - const auto RP3D_RESULT = rigidBody->getTorque(); + const auto& RP3D_RESULT = reinterpret_cast(rp3dBody)->getTorque(); result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z }; } @@ -230,9 +227,9 @@ namespace SHADE { SHVec3 result; - if (rigidBody) + if (rp3dBody) { - const auto RP3D_RESULT = rigidBody->getLinearVelocity(); + const auto& RP3D_RESULT = reinterpret_cast(rp3dBody)->getLinearVelocity(); result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z }; } @@ -243,41 +240,15 @@ namespace SHADE { SHVec3 result; - if (rigidBody) + if (rp3dBody) { - const auto RP3D_RESULT = rigidBody->getAngularVelocity(); + const auto& RP3D_RESULT = reinterpret_cast(rp3dBody)->getAngularVelocity(); result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z }; } return result; } - SHVec3 SHRigidBodyComponent::GetPosition() const noexcept - { - SHVec3 result; - - if (rigidBody) - { - const auto RP3D_RESULT = rigidBody->getTransform().getPosition(); - result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z }; - } - - return result; - } - - SHQuaternion SHRigidBodyComponent::GetOrientation() const noexcept - { - SHQuaternion result; - - if (rigidBody) - { - const auto RP3D_RESULT = rigidBody->getTransform().getOrientation(); - result = SHQuaternion{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z, RP3D_RESULT.w }; - } - - return result; - } - /*-----------------------------------------------------------------------------------*/ /* Setter Function Definitions */ /*-----------------------------------------------------------------------------------*/ @@ -288,43 +259,43 @@ namespace SHADE return; type = newType; - if (rigidBody) - rigidBody->setType(static_cast(newType)); + if (rp3dBody) + reinterpret_cast(rp3dBody)->setType(static_cast(newType)); } void SHRigidBodyComponent::SetMass(float newMass) noexcept { mass = newMass; - if (rigidBody) - rigidBody->setMass(newMass); + if (rp3dBody) + reinterpret_cast(rp3dBody)->setMass(newMass); } void SHRigidBodyComponent::SetDrag(float newDrag) noexcept { drag = newDrag; - if (rigidBody) - rigidBody->setLinearDamping(newDrag); + if (rp3dBody) + reinterpret_cast(rp3dBody)->setLinearDamping(newDrag); } void SHRigidBodyComponent::SetAngularDrag(float newAngularDrag) noexcept { angularDrag = newAngularDrag; - if (rigidBody) - rigidBody->setAngularDamping(newAngularDrag); + if (rp3dBody) + reinterpret_cast(rp3dBody)->setAngularDamping(newAngularDrag); } void SHRigidBodyComponent::SetGravityEnabled(bool enableGravity) noexcept { SetFlag(enableGravity, 0); - if (rigidBody) - rigidBody->enableGravity(enableGravity); + if (rp3dBody) + reinterpret_cast(rp3dBody)->enableGravity(enableGravity); } void SHRigidBodyComponent::SetSleepingEnabled(bool enableSleeping) noexcept { SetFlag(enableSleeping, 1); - if (rigidBody) - rigidBody->setIsAllowedToSleep(enableSleeping); + if (rp3dBody) + reinterpret_cast(rp3dBody)->setIsAllowedToSleep(enableSleeping); } void SHRigidBodyComponent::SetFreezePositionX(bool freezePositionX) noexcept @@ -363,21 +334,26 @@ namespace SHADE SetRP3DAngularConstraints(); } + void SHRigidBodyComponent::SetInterpolate(bool allowInterpolation) noexcept + { + interpolate = allowInterpolation; + } + void SHRigidBodyComponent::SetLinearVelocity(const SHVec3& newLinearVelocity) const noexcept { - if (rigidBody) + if (rp3dBody) { const rp3d::Vector3 NEW_V { newLinearVelocity.x, newLinearVelocity.y, newLinearVelocity.z }; - rigidBody->setLinearVelocity(NEW_V); + reinterpret_cast(rp3dBody)->setLinearVelocity(NEW_V); } } void SHRigidBodyComponent::SetAngularVelocity(const SHVec3& newAngularVelocity) const noexcept { - if (rigidBody) + if (rp3dBody) { const rp3d::Vector3 NEW_V { newAngularVelocity.x, newAngularVelocity.y, newAngularVelocity.z }; - rigidBody->setAngularVelocity(NEW_V); + reinterpret_cast(rp3dBody)->setAngularVelocity(NEW_V); } } @@ -385,79 +361,97 @@ namespace SHADE /* Public Function Member Definitions */ /*-----------------------------------------------------------------------------------*/ + void SHRigidBodyComponent::OnCreate() + { + componentFlags |= 1U << 0; // dirty + componentFlags |= 1U << 1; // rb dirty + componentFlags |= 1U << 2; // has rb + + Synchronise(); + } + + void SHRigidBodyComponent::OnDestroy() + { + componentFlags |= 1U << 0; // dirty + componentFlags |= 1U << 1; // rb dirty + componentFlags &= ~(1U << 2); // no rb + + Synchronise(); + } + void SHRigidBodyComponent::AddForce(const SHVec3& force) const noexcept { - if (rigidBody) + if (rp3dBody) { const rp3d::Vector3 F { force.x, force.y, force.z }; - rigidBody->applyWorldForceAtCenterOfMass(F); + reinterpret_cast(rp3dBody)->applyWorldForceAtCenterOfMass(F); } } void SHRigidBodyComponent::AddForceAtLocalPos(const SHVec3& force, const SHVec3& localPos) const noexcept { - if (rigidBody) + if (rp3dBody) { const rp3d::Vector3 F{ force.x, force.y, force.z }; const rp3d::Vector3 P{ localPos.x, localPos.y, localPos.z }; - rigidBody->applyWorldForceAtLocalPosition(F, P); + reinterpret_cast(rp3dBody)->applyWorldForceAtLocalPosition(F, P); } } void SHRigidBodyComponent::AddForceAtWorldPos(const SHVec3& force, const SHVec3& worldPos) const noexcept { - if (rigidBody) + if (rp3dBody) { const rp3d::Vector3 F{ force.x, force.y, force.z }; const rp3d::Vector3 P{ worldPos.x, worldPos.y, worldPos.z }; - rigidBody->applyWorldForceAtWorldPosition(F, P); + reinterpret_cast(rp3dBody)->applyWorldForceAtWorldPosition(F, P); } } void SHRigidBodyComponent::AddRelativeForce(const SHVec3& relativeForce) const noexcept { - if (rigidBody) + if (rp3dBody) { const rp3d::Vector3 F{ relativeForce.x, relativeForce.y, relativeForce.z }; - rigidBody->applyLocalForceAtCenterOfMass(F); + reinterpret_cast(rp3dBody)->applyLocalForceAtCenterOfMass(F); } } void SHRigidBodyComponent::AddRelativeForceAtLocalPos(const SHVec3& relativeForce, const SHVec3& localPos) const noexcept { - if (rigidBody) + if (rp3dBody) { const rp3d::Vector3 F{ relativeForce.x, relativeForce.y, relativeForce.z }; const rp3d::Vector3 P{ localPos.x, localPos.y, localPos.z }; - rigidBody->applyLocalForceAtLocalPosition(F, P); + reinterpret_cast(rp3dBody)->applyLocalForceAtLocalPosition(F, P); } } void SHRigidBodyComponent::AddRelativeForceAtWorldPos(const SHVec3& relativeForce, const SHVec3& worldPos) const noexcept { - if (rigidBody) + if (rp3dBody) { const rp3d::Vector3 F{ relativeForce.x, relativeForce.y, relativeForce.z }; const rp3d::Vector3 P{ worldPos.x, worldPos.y, worldPos.z }; - rigidBody->applyLocalForceAtWorldPosition(F, P); + reinterpret_cast(rp3dBody)->applyLocalForceAtWorldPosition(F, P); } } void SHRigidBodyComponent::AddTorque(const SHVec3& torque) const noexcept { - if (rigidBody) + if (rp3dBody) { const rp3d::Vector3 T{ torque.x, torque.y, torque.z }; - rigidBody->applyWorldTorque(T); + reinterpret_cast(rp3dBody)->applyWorldTorque(T); } } void SHRigidBodyComponent::AddRelativeTorque(const SHVec3& relativeTorque) const noexcept { - if (rigidBody) + if (rp3dBody) { const rp3d::Vector3 T{ relativeTorque.x, relativeTorque.y, relativeTorque.z }; - rigidBody->applyLocalTorque(T); + reinterpret_cast(rp3dBody)->applyLocalTorque(T); } } @@ -467,6 +461,8 @@ namespace SHADE void SHRigidBodyComponent::SyncRP3DAndSHADE() { + auto* rigidBody = reinterpret_cast(rp3dBody); + rigidBody->setType(static_cast(type)); rigidBody->setMass(mass); @@ -494,8 +490,8 @@ namespace SHADE flags & 1U << 4 ? 1.0f : 0.0f }; - if (rigidBody) - rigidBody->setLinearLockAxisFactor(CONSTRAINTS); + if (rp3dBody) + reinterpret_cast(rp3dBody)->setLinearLockAxisFactor(CONSTRAINTS); } void SHRigidBodyComponent::SetRP3DAngularConstraints() const @@ -507,8 +503,8 @@ namespace SHADE flags & 1U << 7 ? 1.0f : 0.0f }; - if (rigidBody) - rigidBody->setAngularLockAxisFactor(CONSTRAINTS); + if (rp3dBody) + reinterpret_cast(rp3dBody)->setAngularLockAxisFactor(CONSTRAINTS); } } // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h index 668ab6bd..439fa3db 100644 --- a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h +++ b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h @@ -10,16 +10,17 @@ #pragma once -#include - // Project Headers -#include "Math/Vector/SHVec3.h" -#include "Math/SHMatrix.h" #include "ECS_Base/Components/SHComponent.h" +#include "Physics/SHPhysicsObject.h" namespace SHADE { - class SH_API SHRigidBodyComponent : public SHComponent + /*-----------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*-----------------------------------------------------------------------------------*/ + + class SH_API SHRigidBodyComponent : public SHComponent, public SHPhysicsObject { private: /*---------------------------------------------------------------------------------*/ @@ -66,6 +67,7 @@ namespace SHADE [[nodiscard]] bool IsGravityEnabled () const noexcept; [[nodiscard]] bool IsSleepingEnabled () const noexcept; + [[nodiscard]] bool IsInterpolating () const noexcept; [[nodiscard]] Type GetType () const noexcept; [[nodiscard]] float GetMass () const noexcept; @@ -84,8 +86,6 @@ namespace SHADE [[nodiscard]] SHVec3 GetTorque () const noexcept; [[nodiscard]] SHVec3 GetLinearVelocity () const noexcept; [[nodiscard]] SHVec3 GetAngularVelocity () const noexcept; - [[nodiscard]] SHVec3 GetPosition () const noexcept; - [[nodiscard]] SHQuaternion GetOrientation () const noexcept; /*---------------------------------------------------------------------------------*/ /* Setter Functions */ @@ -104,6 +104,7 @@ namespace SHADE void SetFreezeRotationX (bool freezeRotationX) noexcept; void SetFreezeRotationY (bool freezeRotationY) noexcept; void SetFreezeRotationZ (bool freezeRotationZ) noexcept; + void SetInterpolate (bool allowInterpolation) noexcept; void SetLinearVelocity (const SHVec3& newLinearVelocity) const noexcept; void SetAngularVelocity (const SHVec3& newAngularVelocity) const noexcept; @@ -112,6 +113,9 @@ namespace SHADE /* Function Members */ /*---------------------------------------------------------------------------------*/ + void OnCreate () override; + void OnDestroy () override; + void AddForce (const SHVec3& force) const noexcept; void AddForceAtLocalPos (const SHVec3& force, const SHVec3& localPos) const noexcept; void AddForceAtWorldPos (const SHVec3& force, const SHVec3& worldPos) const noexcept; @@ -127,8 +131,6 @@ namespace SHADE /*---------------------------------------------------------------------------------*/ /* Data Members */ /*---------------------------------------------------------------------------------*/ - - rp3d::RigidBody* rigidBody; Type type; @@ -138,6 +140,7 @@ namespace SHADE // rX rY rZ pX pY pZ slp g uint8_t flags; + bool interpolate; /*---------------------------------------------------------------------------------*/ /* Function Members */ diff --git a/SHADE_Engine/src/Physics/SHPhysicsObject.cpp b/SHADE_Engine/src/Physics/SHPhysicsObject.cpp new file mode 100644 index 00000000..4f0616f8 --- /dev/null +++ b/SHADE_Engine/src/Physics/SHPhysicsObject.cpp @@ -0,0 +1,112 @@ +/**************************************************************************************** + * \file SHPhysicsObject.cpp + * \author Diren D Bharwani, diren.dbharwani, 390002520 + * \brief Implementation for a Physics Object. + * + * \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 + +// Primary Header +#include "SHPhysicsObject.h" + +// Project Headers +#include "ECS_Base/Managers/SHSystemManager.h" +#include "SHPhysicsSystem.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Constructors & Destructor Definitions */ + /*-----------------------------------------------------------------------------------*/ + + SHPhysicsObject::SHPhysicsObject() noexcept + : entityID { MAX_EID } + , componentFlags { 0 } + , rp3dBody { nullptr } + {} + + SHPhysicsObject::~SHPhysicsObject() noexcept + { + rp3dBody = nullptr; + } + + /*-----------------------------------------------------------------------------------*/ + /* Getter Function Definitions */ + /*-----------------------------------------------------------------------------------*/ + + SHVec3 SHPhysicsObject::GetPosition() const noexcept + { + SHVec3 result; + + if (rp3dBody) + { + const auto& RP3D_RESULT = rp3dBody->getTransform().getPosition(); + result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z }; + } + + return result; + } + + SHQuaternion SHPhysicsObject::GetOrientation() const noexcept + { + SHQuaternion result; + + if (rp3dBody) + { + const auto& RP3D_RESULT = rp3dBody->getTransform().getOrientation(); + result = SHQuaternion{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z, RP3D_RESULT.w }; + } + + return result; + } + + SHVec3 SHPhysicsObject::GetRotation() const noexcept + { + SHVec3 result; + + if (rp3dBody) + { + const auto& RP3D_RESULT = rp3dBody->getTransform().getOrientation(); + result = SHQuaternion{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z, RP3D_RESULT.w }.ToEuler(); + } + + return result; + } + + /*-----------------------------------------------------------------------------------*/ + /* Public Function Member Definitions */ + /*-----------------------------------------------------------------------------------*/ + + void SHPhysicsObject::Synchronise() const + { + if (const bool IS_DIRTY = componentFlags & 1U << 0; IS_DIRTY) + { + auto* physicsSystem = SHSystemManager::GetSystem(); + + const bool IS_RIGIDBODY_DIRTY = componentFlags & 1U << 1; + const bool IS_COLLIDER_DIRTY = componentFlags & 1U << 3; + + if (IS_RIGIDBODY_DIRTY) + { + static constexpr auto COMP_ENUM = SHPhysicsSystem::UpdateComponent::RIGID_BODY; + + const bool HAS_RIGIDBODY = componentFlags & 1U << 2; + HAS_RIGIDBODY ? physicsSystem->AddComponent(COMP_ENUM, entityID) : physicsSystem->RemoveComponent(COMP_ENUM, entityID); + } + + if (IS_COLLIDER_DIRTY) + { + static constexpr auto COMP_ENUM = SHPhysicsSystem::UpdateComponent::COLLIDER; + + const bool HAS_COLLIDER = componentFlags & 1U << 2; + HAS_COLLIDER ? physicsSystem->AddComponent(COMP_ENUM, entityID) : physicsSystem->RemoveComponent(COMP_ENUM, entityID); + } + } + } + + +} // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHPhysicsObject.h b/SHADE_Engine/src/Physics/SHPhysicsObject.h new file mode 100644 index 00000000..20449f2d --- /dev/null +++ b/SHADE_Engine/src/Physics/SHPhysicsObject.h @@ -0,0 +1,82 @@ +/**************************************************************************************** + * \file SHPhysicsObject.h + * \author Diren D Bharwani, diren.dbharwani, 390002520 + * \brief Interface for a Physics Object. + * + * \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 + +// Project Headers +#include "Math/Vector/SHVec3.h" +#include "Math/SHQuaternion.h" +#include "ECS_Base/Entity/SHEntity.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*-----------------------------------------------------------------------------------*/ + + class SH_API SHPhysicsObject + { + protected: + /*---------------------------------------------------------------------------------*/ + /* Friends */ + /*---------------------------------------------------------------------------------*/ + + friend class SHPhysicsSystem; + + public: + /*---------------------------------------------------------------------------------*/ + /* Constructors & Destructor */ + /*---------------------------------------------------------------------------------*/ + + SHPhysicsObject () noexcept; + SHPhysicsObject (const SHPhysicsObject& rhs) noexcept = default; + SHPhysicsObject (SHPhysicsObject&& rhs) noexcept = default; + ~SHPhysicsObject () noexcept; + + /*---------------------------------------------------------------------------------*/ + /* Operator Overloads */ + /*---------------------------------------------------------------------------------*/ + + SHPhysicsObject& operator=(const SHPhysicsObject& rhs) noexcept = default; + SHPhysicsObject& operator=(SHPhysicsObject&& rhs) noexcept = default; + + /*---------------------------------------------------------------------------------*/ + /* Getter Functions */ + /*---------------------------------------------------------------------------------*/ + + [[nodiscard]] SHVec3 GetPosition () const noexcept; + [[nodiscard]] SHQuaternion GetOrientation () const noexcept; + [[nodiscard]] SHVec3 GetRotation () const noexcept; + + /*---------------------------------------------------------------------------------*/ + /* Function Members */ + /*---------------------------------------------------------------------------------*/ + + /** + * @brief Checks for updates in the component states and tells the physics system to + * make any necessary additions / removals to rp3d side to sync with the SHADE + * component. + */ + void Synchronise() const; + + protected: + /*---------------------------------------------------------------------------------*/ + /* Data Members */ + /*---------------------------------------------------------------------------------*/ + + EntityID entityID; + uint8_t componentFlags; // 0 0 0 c cDirty rb rbDirty dirty + rp3d::CollisionBody* rp3dBody; // Can be either a collision body or a rigid body + rp3d::Transform prevTransform; // Cached transform for interpolation + + }; +} // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp b/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp index 537c2c70..d27469ad 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp +++ b/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp @@ -14,11 +14,10 @@ #include "SHPhysicsSystem.h" // Project Headers -#include "Math/Transform/SHTransformComponent.h" -#include "Scene/SHSceneManager.h" #include "ECS_Base/Managers/SHComponentManager.h" #include "ECS_Base/Managers/SHEntityManager.h" -#include "Graphics/MiddleEnd/Interface/SHRenderable.h" +#include "Scene/SHSceneManager.h" +#include "Math/Transform/SHTransformComponent.h" namespace SHADE { @@ -26,6 +25,12 @@ namespace SHADE /* Constructors & Destructor Definitions */ /*-----------------------------------------------------------------------------------*/ + SHPhysicsSystem::SHPhysicsSystem() + : accumulatedTime { 0.0 } + , fixedDT { 1.0 / 60.0 } + , world { nullptr } + {} + SHPhysicsSystem::PhysicsPreUpdate::PhysicsPreUpdate() : SHSystemRoutine { "Physics PreUpdate", true } {} @@ -51,11 +56,6 @@ namespace SHADE return false; } - //double SHPhysicsSystem::GetFixedUpdate() const noexcept - //{ - // return fixedUpdate; - //} - SHVec3 SHPhysicsSystem::GetWorldGravity() const noexcept { SHVec3 result; @@ -97,12 +97,6 @@ namespace SHADE /* Setter Function Definitions */ /*-----------------------------------------------------------------------------------*/ - //void SHPhysicsSystem::SetFixedUpdate(double fixedUpdateRate) noexcept - //{ - // fixedUpdate = fixedUpdateRate; - // SHLOG_INFO("Setting Physics update rate to {}", 1.0 / fixedUpdate) - //} - void SHPhysicsSystem::SetWorldGravity(const SHVec3& gravity) const noexcept { if (world) @@ -178,7 +172,7 @@ namespace SHADE // Create a physics world with the default settings PhysicsWorld::WorldSettings settings; - settings.gravity = Vector3{ 0, -9.81, 0 }; + settings.gravity = Vector3{ 0.0f, -9.81f, 0.0f }; settings.isSleepingEnabled = true; settings.defaultVelocitySolverNbIterations = 8; settings.defaultPositionSolverNbIterations = 3; @@ -194,108 +188,14 @@ namespace SHADE factory.destroyPhysicsWorld(world); } - void SHPhysicsSystem::AddRigidBodyComponent(EntityID id) noexcept - { - const UpdateCommand NEW_CMD - { - .component = UpdateComponent::RIGID_BODY, - .type = UpdateType::ADD, - .entityID = id - }; - - updateQueue.push(NEW_CMD); - } - - void SHPhysicsSystem::AddColliderComponent(EntityID id) noexcept - { - const UpdateCommand NEW_CMD - { - .component = UpdateComponent::COLLIDER, - .type = UpdateType::ADD, - .entityID = id - }; - - updateQueue.push(NEW_CMD); - } - - void SHPhysicsSystem::RemoveRigidBodyComponent(EntityID id) noexcept - { - const UpdateCommand NEW_CMD - { - .component = UpdateComponent::RIGID_BODY, - .type = UpdateType::REMOVE, - .entityID = id - }; - - updateQueue.push(NEW_CMD); - } - - void SHPhysicsSystem::RemoveColliderComponent(EntityID id) noexcept - { - const UpdateCommand NEW_CMD - { - .component = UpdateComponent::COLLIDER, - .type = UpdateType::REMOVE, - .entityID = id - }; - - updateQueue.push(NEW_CMD); - } - void SHPhysicsSystem::PhysicsPreUpdate::Execute([[maybe_unused]]double dt) noexcept { auto* system = reinterpret_cast(GetSystem()); + system->ClearUpdateQueue(); - - // Sync active states: if node or component is not active, set rp3d to inactive - static const auto SYNC_ACTIVE = [](SHSceneNode* node) - { - const EntityID ENTITY_ID = node->GetEntityID(); - - // Check if has rigid body - auto const* rigidBodyComponent = SHComponentManager::GetComponent_s(ENTITY_ID); - if(rigidBodyComponent) - { - const bool RP3D_ACTIVE = rigidBodyComponent->rigidBody->isActive(); - const bool SHADE_ACTIVE = node->IsActive() && rigidBodyComponent->isActive; - - if (RP3D_ACTIVE != SHADE_ACTIVE) - rigidBodyComponent->rigidBody->setIsActive(SHADE_ACTIVE); - } - else // Check for a collider - { - - } - }; - - const auto& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); - sceneGraph.Traverse(SYNC_ACTIVE); + system->SyncActiveStates(SHSceneManager::GetCurrentSceneGraph()); } - //void SHPhysicsSystem::PhysicsFixedUpdate::Execute(double dt) noexcept - //{ - // // I had to override this anyway due to needing to calculate the - // // interpolation factor right after the fixed update was done - - // auto* system = reinterpret_cast(GetSystem()); - // fixedTimeStep = 1.0 / system->fixedUpdate; - - // accumulatedTime += dt; - // int counter = 0; - - // while (accumulatedTime > fixedTimeStep) - // { - // FixedExecute(fixedTimeStep); - - // accumulatedTime -= fixedTimeStep; - // ++counter; - // } - - // stats.numSteps = counter; - - // system->interpolationFactor = accumulatedTime / fixedTimeStep; - //} - void SHPhysicsSystem::PhysicsFixedUpdate::FixedExecute(double dt) noexcept { auto* system = reinterpret_cast(GetSystem()); @@ -309,38 +209,25 @@ namespace SHADE { // Interpolate transforms for rendering const auto& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); - sceneGraph.Traverse([](SHSceneNode* node) - { - const EntityID ENTITY_ID = node->GetEntityID(); - - // Check if has rigid body - if (auto* rb = SHComponentManager::GetComponent_s(ENTITY_ID); rb) - { - // TODO(Diren): Interpolate transforms for rendering - if (node->IsActive() && rb->isActive) - { - // Get SHADE transform - auto* transformComponent = SHComponentManager::GetComponent_s(ENTITY_ID); - SHASSERT(transformComponent != nullptr, "Transform Component missing from Entity " + std::to_string(ENTITY_ID)) - - const auto& RP3D_POS = rb->GetPosition(); - const SHVec3 SHADE_POS{ RP3D_POS.x, RP3D_POS.y, RP3D_POS.z }; - - const auto& SHADE_ROT = rb->GetOrientation().ToEuler(); - - transformComponent->SetWorldPosition(SHADE_POS); - transformComponent->SetWorldRotation(SHADE_ROT); - } - else // Check for a collider - { - - } - } - }); // TODO(Diren): Handle trigger messages for scripting } + /*-----------------------------------------------------------------------------------*/ + /* Protected Function Member Definitions */ + /*-----------------------------------------------------------------------------------*/ + + void SHPhysicsSystem::AddComponent(UpdateComponent comp, EntityID entityID) noexcept + { + updateQueue.push({ comp, UpdateType::ADD, entityID }); + } + + + void SHPhysicsSystem::RemoveComponent(UpdateComponent comp, EntityID entityID) noexcept + { + updateQueue.push({ comp, UpdateType::REMOVE, entityID }); + } + /*-----------------------------------------------------------------------------------*/ /* Private Function Member Definitions */ /*-----------------------------------------------------------------------------------*/ @@ -377,6 +264,85 @@ namespace SHADE } } + void SHPhysicsSystem::SyncActiveStates(const SHSceneGraph& sceneGraph) const noexcept + { + // Sync active states: if node or component is not active, set rp3d to inactive + static constexpr auto SYNC_ACTIVE = [](SHSceneNode* node) + { + const EntityID ENTITY_ID = node->GetEntityID(); + + // Check if has rigid body + auto const* rigidBodyComponent = SHComponentManager::GetComponent_s(ENTITY_ID); + if(rigidBodyComponent) + { + const bool RP3D_ACTIVE = rigidBodyComponent->rp3dBody->isActive(); + const bool SHADE_ACTIVE = node->IsActive() && rigidBodyComponent->isActive; + + if (RP3D_ACTIVE != SHADE_ACTIVE) + rigidBodyComponent->rp3dBody->setIsActive(SHADE_ACTIVE); + } + else // Check for a collider + { + + } + }; + + sceneGraph.Traverse(SYNC_ACTIVE); + } + + void SHPhysicsSystem::SyncTransforms(const SHSceneGraph& sceneGraph) const noexcept + { + const rp3d::decimal INTERPOLATION_FACTOR = static_cast(accumulatedTime / fixedDT); + + static const auto SYNC_TRANSFORMS = [&](SHSceneNode* node) + { + const EntityID ENTITY_ID = node->GetEntityID(); + + // Check if has rigid body + if (auto* rb = SHComponentManager::GetComponent_s(ENTITY_ID); rb) + { + if (node->IsActive() && rb->isActive) + { + // Get SHADE transform + auto* transformComponent = SHComponentManager::GetComponent_s(ENTITY_ID); + SHASSERT(transformComponent != nullptr, "Transform Component missing from Entity " + std::to_string(ENTITY_ID)) + + SHVec3 shadePos, shadeRot; + + if (rb->interpolate) + { + const rp3d::Transform CURRENT_TRANSFORM = rb->rp3dBody->getTransform(); + const rp3d::Transform INTERPOLATED_TRANSFORM = rp3d::Transform::interpolateTransforms(rb->prevTransform, CURRENT_TRANSFORM, INTERPOLATION_FACTOR); + + const auto& RP3D_POS = INTERPOLATED_TRANSFORM.getPosition(); + shadePos = SHVec3{ RP3D_POS.x, RP3D_POS.y, RP3D_POS.z }; + + const auto& RP3D_ORT = INTERPOLATED_TRANSFORM.getOrientation(); + shadeRot = SHQuaternion{ RP3D_ORT.x, RP3D_ORT.y, RP3D_ORT.z, RP3D_ORT.w }.ToEuler(); + + rb->prevTransform = CURRENT_TRANSFORM; + } + else + { + + const auto& RP3D_POS = rb->GetPosition(); + shadePos = SHVec3{ RP3D_POS.x, RP3D_POS.y, RP3D_POS.z }; + shadeRot = rb->GetOrientation().ToEuler(); + } + + transformComponent->SetWorldPosition(shadePos); + transformComponent->SetWorldRotation(shadeRot); + } + else // Check for a collider + { + + } + } + }; + + sceneGraph.Traverse(SYNC_TRANSFORMS); + } + void SHPhysicsSystem::AddRigidBody(EntityID entityID) const noexcept { @@ -413,7 +379,8 @@ namespace SHADE rigidBodyComponent = SHComponentManager::GetComponent(entityID); } - rigidBodyComponent->rigidBody = world->createRigidBody(RP3D_TF); + rigidBodyComponent->rp3dBody = world->createRigidBody(RP3D_TF); + rigidBodyComponent->prevTransform = RP3D_TF; rigidBodyComponent->SyncRP3DAndSHADE(); // Reassign collider @@ -438,9 +405,8 @@ namespace SHADE // If a collider exists, remake the colliders with a collision body - world->destroyRigidBody(rigidBodyComponent->rigidBody); - rigidBodyComponent->rigidBody = nullptr; // this should be redundant + world->destroyRigidBody(reinterpret_cast(rigidBodyComponent->rp3dBody)); + rigidBodyComponent->rp3dBody = nullptr; // this should be redundant } - } // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHPhysicsSystem.h b/SHADE_Engine/src/Physics/SHPhysicsSystem.h index dac6836a..273eb54d 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsSystem.h +++ b/SHADE_Engine/src/Physics/SHPhysicsSystem.h @@ -11,14 +11,12 @@ #pragma once #include -#include #include // Project Headers #include "Math/SHQuaternion.h" #include "Components/SHRigidBodyComponent.h" - #include "Scene/SHSceneGraph.h" #include "ECS_Base/System/SHSystemRoutine.h" #include "ECS_Base/System/SHFixedSystemRoutine.h" @@ -31,6 +29,13 @@ namespace SHADE class SH_API SHPhysicsSystem : public SHSystem { + protected: + /*---------------------------------------------------------------------------------*/ + /* Friends */ + /*---------------------------------------------------------------------------------*/ + + friend class SHPhysicsObject; + public: /*---------------------------------------------------------------------------------*/ /* Type Definitions */ @@ -48,18 +53,7 @@ namespace SHADE /* Constructors & Destructor */ /*---------------------------------------------------------------------------------*/ - SHPhysicsSystem () = default; - ~SHPhysicsSystem () override = default; - - SHPhysicsSystem (const SHPhysicsSystem&) = delete; - SHPhysicsSystem (SHPhysicsSystem&&) = delete; - - /*---------------------------------------------------------------------------------*/ - /* Operator Overloads */ - /*---------------------------------------------------------------------------------*/ - - SHPhysicsSystem& operator= (const SHPhysicsSystem&) = delete; - SHPhysicsSystem& operator= (SHPhysicsSystem&&) = delete; + SHPhysicsSystem(); /*---------------------------------------------------------------------------------*/ /* Getter Functions */ @@ -67,7 +61,6 @@ namespace SHADE [[nodiscard]] bool IsSleepingEnabled () const noexcept; - //[[nodiscard]] double GetFixedUpdate () const noexcept; [[nodiscard]] SHVec3 GetWorldGravity () const noexcept; [[nodiscard]] uint16_t GetNumberVelocityIterations () const noexcept; [[nodiscard]] uint16_t GetNumberPositionIterations () const noexcept; @@ -92,11 +85,6 @@ namespace SHADE void Init () override; void Exit () override; - void AddRigidBodyComponent (EntityID id) noexcept; - void AddColliderComponent (EntityID id) noexcept; - void RemoveRigidBodyComponent (EntityID id) noexcept; - void RemoveColliderComponent (EntityID id) noexcept; - /*---------------------------------------------------------------------------------*/ /* System Routines */ /*---------------------------------------------------------------------------------*/ @@ -109,17 +97,6 @@ namespace SHADE /*-------------------------------------------------------------------------------*/ PhysicsPreUpdate(); - ~PhysicsPreUpdate() = default; - - PhysicsPreUpdate(const PhysicsPreUpdate&) = delete; - PhysicsPreUpdate(PhysicsPreUpdate&&) = delete; - - /*-------------------------------------------------------------------------------*/ - /* Operator Overloads */ - /*-------------------------------------------------------------------------------*/ - - PhysicsPreUpdate& operator= (const PhysicsPreUpdate&) = delete; - PhysicsPreUpdate& operator= (PhysicsPreUpdate&&) = delete; /*-------------------------------------------------------------------------------*/ /* Function Members */ @@ -136,17 +113,6 @@ namespace SHADE /*-------------------------------------------------------------------------------*/ PhysicsFixedUpdate(); - ~PhysicsFixedUpdate() = default; - - PhysicsFixedUpdate(const PhysicsFixedUpdate&) = delete; - PhysicsFixedUpdate(PhysicsFixedUpdate&&) = delete; - - /*-------------------------------------------------------------------------------*/ - /* Operator Overloads */ - /*-------------------------------------------------------------------------------*/ - - PhysicsFixedUpdate& operator= (const PhysicsFixedUpdate&) = delete; - PhysicsFixedUpdate& operator= (PhysicsFixedUpdate&&) = delete; /*-------------------------------------------------------------------------------*/ /* Function Members */ @@ -164,17 +130,6 @@ namespace SHADE /*-------------------------------------------------------------------------------*/ PhysicsPostUpdate(); - ~PhysicsPostUpdate() = default; - - PhysicsPostUpdate(const PhysicsPostUpdate&) = delete; - PhysicsPostUpdate(PhysicsPostUpdate&&) = delete; - - /*-------------------------------------------------------------------------------*/ - /* Operator Overloads */ - /*-------------------------------------------------------------------------------*/ - - PhysicsPostUpdate& operator= (const PhysicsPostUpdate&) = delete; - PhysicsPostUpdate& operator= (PhysicsPostUpdate&&) = delete; /*-------------------------------------------------------------------------------*/ /* Function Members */ @@ -183,8 +138,7 @@ namespace SHADE void Execute(double dt) noexcept override; }; - - private: + protected: /*---------------------------------------------------------------------------------*/ /* Type Definitions */ /*---------------------------------------------------------------------------------*/ @@ -199,38 +153,41 @@ namespace SHADE EntityID entityID; }; - struct CachedTransform - { - SHVec3 position; - SHQuaternion orientation; - }; + /*---------------------------------------------------------------------------------*/ + /* Function Members */ + /*---------------------------------------------------------------------------------*/ + void AddComponent (UpdateComponent comp, EntityID entityID) noexcept; + void RemoveComponent (UpdateComponent comp, EntityID entityID) noexcept; + + private: /*---------------------------------------------------------------------------------*/ /* Data Members */ /*---------------------------------------------------------------------------------*/ - //double interpolationFactor; - //double fixedUpdate; + // TODO(Diren): Store interpFactor & fixedUpdate for modifiable fixedDT - double accumulatedTime; - double fixedDT; + double accumulatedTime; + double fixedDT; - rp3d::PhysicsCommon factory; - rp3d::PhysicsWorld* world; + rp3d::PhysicsCommon factory; + rp3d::PhysicsWorld* world; - std::queue updateQueue; - std::unordered_map prevTransforms; // used for interpolation + std::queue updateQueue; /*---------------------------------------------------------------------------------*/ /* Function Members */ /*---------------------------------------------------------------------------------*/ - void ClearUpdateQueue () noexcept; + void ClearUpdateQueue () noexcept; + void SyncActiveStates (const SHSceneGraph& sceneGraph) const noexcept; + void SyncTransforms (const SHSceneGraph& sceneGraph) const noexcept; + // TODO(Diren): Trigger handling - void AddRigidBody (EntityID entityID) const noexcept; - void AddCollider (EntityID entityID) const noexcept; - void RemoveRigidBody (EntityID entityID) const noexcept; - void RemoveCollider (EntityID entityID) const noexcept; + void AddRigidBody (EntityID entityID) const noexcept; + void AddCollider (EntityID entityID) const noexcept; + void RemoveRigidBody (EntityID entityID) const noexcept; + void RemoveCollider (EntityID entityID) const noexcept; }; From dc8d58d95caf0c8fa3fca7e61f17e6618d04035b Mon Sep 17 00:00:00 2001 From: mushgunAX Date: Sat, 1 Oct 2022 13:49:11 +0800 Subject: [PATCH 05/17] fix GetMouseWindowPosition() --- SHADE_Engine/src/Input/SHInputManagerSystem.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SHADE_Engine/src/Input/SHInputManagerSystem.h b/SHADE_Engine/src/Input/SHInputManagerSystem.h index eb40b240..2a8fe052 100644 --- a/SHADE_Engine/src/Input/SHInputManagerSystem.h +++ b/SHADE_Engine/src/Input/SHInputManagerSystem.h @@ -417,8 +417,8 @@ namespace SHADE { POINT p{ mouseScreenX, mouseScreenY }; ScreenToClient(GetActiveWindow(), &p); - if (x) *x = mouseScreenX; - if (y) *y = mouseScreenY; + if (x) *x = p.x; + if (y) *y = p.y; } //Get the mouse velocity From 0360a8bfa145c4773755ff2ba3a4cc36d825d86b Mon Sep 17 00:00:00 2001 From: mushgunAX Date: Sat, 1 Oct 2022 14:34:30 +0800 Subject: [PATCH 06/17] made the Input Manager NOT be a System anymore --- .../src/Application/SBApplication.cpp | 5 +- .../src/Graphics/Windowing/SHWindow.cpp | 7 +- ...utManagerSystem.cpp => SHInputManager.cpp} | 80 +++++++------------ ...HInputManagerSystem.h => SHInputManager.h} | 33 +++----- 4 files changed, 42 insertions(+), 83 deletions(-) rename SHADE_Engine/src/Input/{SHInputManagerSystem.cpp => SHInputManager.cpp} (60%) rename SHADE_Engine/src/Input/{SHInputManagerSystem.h => SHInputManager.h} (93%) diff --git a/SHADE_Application/src/Application/SBApplication.cpp b/SHADE_Application/src/Application/SBApplication.cpp index 3e9b0dce..700b36e3 100644 --- a/SHADE_Application/src/Application/SBApplication.cpp +++ b/SHADE_Application/src/Application/SBApplication.cpp @@ -23,7 +23,7 @@ #include "Graphics/MiddleEnd/Interface/SHRenderable.h" #include "Scene/SHSceneManager.h" #include "Math/Transform/SHTransformSystem.h" -#include "Input/SHInputManagerSystem.h" +#include "Input/SHInputManager.h" #include "FRC/SHFramerateController.h" //#include "AudioSystem/SHAudioSystem.h" @@ -58,7 +58,6 @@ namespace Sandbox // TODO(Diren): Create Physics System here SHADE::SHSystemManager::CreateSystem(); SHADE::SHGraphicsSystem* graphicsSystem = static_cast(SHADE::SHSystemManager::GetSystem()); - SHADE::SHSystemManager::CreateSystem(); //SHADE::SHSystemManager::CreateSystem(); // Create Routines @@ -80,8 +79,6 @@ namespace Sandbox SHADE::SHComponentManager::CreateComponentSparseSet(); SHADE::SHComponentManager::CreateComponentSparseSet(); - SHADE::SHSystemManager::RegisterRoutine(); - //TODO: REMOVE AFTER PRESENTATION SHADE::SHAssetManager::LoadDataTemp("../../Assets/racoon.gltf"); SHADE::SHAssetManager::LoadDataTemp("../../Assets/RaccoonBag_Color_Ver4.dds"); diff --git a/SHADE_Engine/src/Graphics/Windowing/SHWindow.cpp b/SHADE_Engine/src/Graphics/Windowing/SHWindow.cpp index 4d8dae72..3a1deb00 100644 --- a/SHADE_Engine/src/Graphics/Windowing/SHWindow.cpp +++ b/SHADE_Engine/src/Graphics/Windowing/SHWindow.cpp @@ -2,7 +2,7 @@ #include "SHWindowMap.h" #include "SHWindow.h" #include "ECS_Base/Managers/SHSystemManager.h" -#include "Input/SHInputManagerSystem.h" +#include "Input/SHInputManager.h" namespace SHADE @@ -343,10 +343,7 @@ namespace SHADE } case WM_MOUSEWHEEL: { - if (auto im = SHSystemManager::GetSystem()) - { - im->PollWheelVerticalDelta(wparam); - } + SHInputManager::PollWheelVerticalDelta(wparam); break; } default: diff --git a/SHADE_Engine/src/Input/SHInputManagerSystem.cpp b/SHADE_Engine/src/Input/SHInputManager.cpp similarity index 60% rename from SHADE_Engine/src/Input/SHInputManagerSystem.cpp rename to SHADE_Engine/src/Input/SHInputManager.cpp index 1beabe3f..619afec0 100644 --- a/SHADE_Engine/src/Input/SHInputManagerSystem.cpp +++ b/SHADE_Engine/src/Input/SHInputManager.cpp @@ -1,5 +1,5 @@ /********************************************************************* - * \file SHInputManagerSystem.cpp + * \file SHInputManager.cpp * \author Ryan Wang Nian Jing * \brief Definition of input manager. * Handles input from keyboard and mouse. Soon to include controller. @@ -11,7 +11,8 @@ #pragma once #include -#include "SHInputManagerSystem.h" +#include "SHInputManager.h" +#include "../Tools/SHException.h" namespace SHADE { @@ -19,61 +20,34 @@ namespace SHADE /* Static defines */ /*------------------------------------------------------------------------*/ - unsigned SHInputManagerSystem::keyCount = 0; - bool SHInputManagerSystem::keys[MAX_KEYS]; - bool SHInputManagerSystem::keysLast[MAX_KEYS]; - double SHInputManagerSystem::keysHeldTime[MAX_KEYS]; - double SHInputManagerSystem::keysReleasedTime[MAX_KEYS]; + unsigned SHInputManager::keyCount = 0; + bool SHInputManager::keys[MAX_KEYS]; + bool SHInputManager::keysLast[MAX_KEYS]; + double SHInputManager::keysHeldTime[MAX_KEYS]; + double SHInputManager::keysReleasedTime[MAX_KEYS]; - unsigned SHInputManagerSystem::keyToggleCount = 0; - bool SHInputManagerSystem::keysToggle[MAX_KEYS]; - bool SHInputManagerSystem::keysToggleLast[MAX_KEYS]; - double SHInputManagerSystem::keysToggleOnTime[MAX_KEYS]; - double SHInputManagerSystem::keysToggleOffTime[MAX_KEYS]; + unsigned SHInputManager::keyToggleCount = 0; + bool SHInputManager::keysToggle[MAX_KEYS]; + bool SHInputManager::keysToggleLast[MAX_KEYS]; + double SHInputManager::keysToggleOnTime[MAX_KEYS]; + double SHInputManager::keysToggleOffTime[MAX_KEYS]; - int SHInputManagerSystem::mouseScreenX = 0; - int SHInputManagerSystem::mouseScreenY = 0; - int SHInputManagerSystem::mouseScreenXLast = 0; - int SHInputManagerSystem::mouseScreenYLast = 0; - double SHInputManagerSystem::mouseVelocityX = 0; - double SHInputManagerSystem::mouseVelocityY = 0; - int SHInputManagerSystem::mouseWheelVerticalDelta = 0; - int SHInputManagerSystem::mouseWheelVerticalDeltaPoll = 0; + int SHInputManager::mouseScreenX = 0; + int SHInputManager::mouseScreenY = 0; + int SHInputManager::mouseScreenXLast = 0; + int SHInputManager::mouseScreenYLast = 0; + double SHInputManager::mouseVelocityX = 0; + double SHInputManager::mouseVelocityY = 0; + int SHInputManager::mouseWheelVerticalDelta = 0; + int SHInputManager::mouseWheelVerticalDeltaPoll = 0; - void SHInputManagerSystem::Init() - { - keyCount = 0; - SecureZeroMemory(keys, sizeof(keys)); - SecureZeroMemory(keysLast, sizeof(keysLast)); - SecureZeroMemory(keysHeldTime, sizeof(keysHeldTime)); - SecureZeroMemory(keysReleasedTime, sizeof(keysReleasedTime)); - - keyToggleCount = 0; - SecureZeroMemory(keysToggle, sizeof(keysToggle)); - SecureZeroMemory(keysToggleLast, sizeof(keysToggleLast)); - SecureZeroMemory(keysToggleOnTime, sizeof(keysToggleOnTime)); - SecureZeroMemory(keysToggleOffTime, sizeof(keysToggleOffTime)); - - mouseScreenX = 0; - mouseScreenY = 0; - mouseScreenXLast = 0; - mouseScreenYLast = 0; - mouseWheelVerticalDelta = 0; - mouseWheelVerticalDeltaPoll = 0; - } - - void SHInputManagerSystem::Exit() - { - //No dynamically allocated memory. Nothing to do here. - } - - void SHInputManagerSystem::InputManagerRoutine:: - FixedExecute(double dt) noexcept + void SHInputManager::UpdateInput(double dt) noexcept { //Keyboard and Mouse Buttons//////////////////////////////////////////////// //Poll unsigned char keyboardState[MAX_KEYS]; - GetKeyboardState(keyboardState); + //if (GetKeyboardState(keyboardState) == false) return; + SHASSERT(GetKeyboardState(keyboardState), "SHInputManager:GetKeyboardState() failed ({})", GetLastError()); keyCount = 0; keyToggleCount = 0; for (size_t i = 0; i < MAX_KEYS; ++i) @@ -144,7 +118,7 @@ namespace SHADE mouseWheelVerticalDeltaPoll = 0; } - bool SHInputManagerSystem::AnyKeyDown(SH_KEYCODE* firstDetected) noexcept + bool SHInputManager::AnyKeyDown(SH_KEYCODE* firstDetected) noexcept { for (size_t i = 0; i < MAX_KEYS; ++i) { @@ -157,7 +131,7 @@ namespace SHADE return false; } - bool SHInputManagerSystem::AnyKey(SH_KEYCODE* firstDetected) noexcept + bool SHInputManager::AnyKey(SH_KEYCODE* firstDetected) noexcept { for (size_t i = 0; i < MAX_KEYS; ++i) { @@ -170,7 +144,7 @@ namespace SHADE return false; } - bool SHInputManagerSystem::AnyKeyUp(SH_KEYCODE* firstDetected) noexcept + bool SHInputManager::AnyKeyUp(SH_KEYCODE* firstDetected) noexcept { for (size_t i = 0; i < MAX_KEYS; ++i) { diff --git a/SHADE_Engine/src/Input/SHInputManagerSystem.h b/SHADE_Engine/src/Input/SHInputManager.h similarity index 93% rename from SHADE_Engine/src/Input/SHInputManagerSystem.h rename to SHADE_Engine/src/Input/SHInputManager.h index 2a8fe052..d3e31004 100644 --- a/SHADE_Engine/src/Input/SHInputManagerSystem.h +++ b/SHADE_Engine/src/Input/SHInputManager.h @@ -1,5 +1,5 @@ /********************************************************************* - * \file SHInputManagerSystem.h + * \file SHInputManager.h * \author Ryan Wang Nian Jing * \brief Declaration of input manager. * Handles input from keyboard and mouse. Soon to include controller. @@ -13,19 +13,12 @@ //#include //#include "../../SHADE_Managed/src/SHpch.h" #include "SH_API.h" -#include "ECS_Base/System/SHSystem.h" -#include "ECS_Base/System/SHFixedSystemRoutine.h" namespace SHADE { - class SH_API SHInputManagerSystem : public SHSystem + class SH_API SHInputManager { public: - class SH_API InputManagerRoutine : public SHFixedSystemRoutine - { - public: - virtual void FixedExecute(double dt) noexcept override final; - }; public: /*------------------------------------------------------------------------*/ @@ -276,23 +269,21 @@ namespace SHADE }; public: + //Updates current state of the input, with dt to be fetched from FRC + //TODO should dt be fixed or variable? + static void UpdateInput(double dt) noexcept; + /*------------------------------------------------------------------------*/ /* Constructors & Destructor */ /*------------------------------------------------------------------------*/ - SHInputManagerSystem() noexcept = default; - ~SHInputManagerSystem() noexcept = default; + SHInputManager() noexcept = default; + ~SHInputManager() noexcept = default; - SHInputManagerSystem(const SHInputManagerSystem&) = delete; - SHInputManagerSystem(SHInputManagerSystem&&) = delete; + SHInputManager(const SHInputManager&) = delete; + SHInputManager(SHInputManager&&) = delete; - SHInputManagerSystem& operator= (const SHInputManagerSystem&) = delete; - SHInputManagerSystem& operator= (SHInputManagerSystem&&) = delete; - - /*------------------------------------------------------------------------*/ - /* SHSystem Overrides */ - /*------------------------------------------------------------------------*/ - virtual void Init() override final; - virtual void Exit() override final; + SHInputManager& operator= (const SHInputManager&) = delete; + SHInputManager& operator= (SHInputManager&&) = delete; /*------------------------------------------------------------------------*/ /* Member Functions */ From 0c78eca1bce62b4e94fc91bc9265b425609557e1 Mon Sep 17 00:00:00 2001 From: Glence Date: Sat, 1 Oct 2022 15:09:26 +0800 Subject: [PATCH 07/17] added audiosystem back in added a button for the audio --- SHADE_Application/src/Application/SBApplication.cpp | 6 +++--- SHADE_Engine/src/AudioSystem/SHAudioSystem.cpp | 4 ++-- .../src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp | 6 ++++++ 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/SHADE_Application/src/Application/SBApplication.cpp b/SHADE_Application/src/Application/SBApplication.cpp index 8abc341b..b982557c 100644 --- a/SHADE_Application/src/Application/SBApplication.cpp +++ b/SHADE_Application/src/Application/SBApplication.cpp @@ -25,7 +25,7 @@ #include "Math/Transform/SHTransformSystem.h" #include "Input/SHInputManagerSystem.h" #include "FRC/SHFramerateController.h" -//#include "AudioSystem/SHAudioSystem.h" +#include "AudioSystem/SHAudioSystem.h" #include "Scenes/SBTestScene.h" #include "Math/Transform/SHTransformComponent.h" @@ -59,7 +59,7 @@ namespace Sandbox SHADE::SHSystemManager::CreateSystem(); SHADE::SHGraphicsSystem* graphicsSystem = static_cast(SHADE::SHSystemManager::GetSystem()); SHADE::SHSystemManager::CreateSystem(); - //SHADE::SHSystemManager::CreateSystem(); + SHADE::SHSystemManager::CreateSystem(); // Create Routines SHADE::SHSystemManager::RegisterRoutine(); @@ -95,7 +95,7 @@ namespace Sandbox auto id2 = SHFamilyID::GetID(); auto id3 = SHFamilyID::GetID(); - //SHADE::SHSystemManager::RegisterRoutine(); + SHADE::SHSystemManager::RegisterRoutine(); // Set up graphics system and windows graphicsSystem->SetWindow(&window); diff --git a/SHADE_Engine/src/AudioSystem/SHAudioSystem.cpp b/SHADE_Engine/src/AudioSystem/SHAudioSystem.cpp index be9ee832..2482fe8e 100644 --- a/SHADE_Engine/src/AudioSystem/SHAudioSystem.cpp +++ b/SHADE_Engine/src/AudioSystem/SHAudioSystem.cpp @@ -93,8 +93,8 @@ namespace SHADE void SHADE::SHAudioSystem::Run(float dt) { static_cast(dt); - if (GetKeyState(VK_SPACE) & 0x8000) - PlayEventOnce("event:/Characters/sfx_footsteps_raccoon"); + //if (GetKeyState(VK_SPACE) & 0x8000) + // PlayEventOnce("event:/Characters/sfx_footsteps_raccoon"); fmodStudioSystem->update(); if (!denseListener->empty()) diff --git a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp index 25d3d955..35836dc2 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/Inspector/SHEditorInspector.cpp @@ -45,6 +45,12 @@ namespace SHADE SHEditorWindow::Update(); if (Begin()) { + if (ImGui::Button("AUDIO")) + { + auto audioSystem = SHSystemManager::GetSystem(); + audioSystem->PlayEventOnce("event:/Characters/sfx_footsteps_raccoon"); + } + if (!SHEditor::selectedEntities.empty()) { EntityID const& eid = SHEditor::selectedEntities[0]; From 4f56a32a9bbe26b258b5e5b16d4bc122f6e51ce9 Mon Sep 17 00:00:00 2001 From: Diren D Bharwani Date: Sat, 1 Oct 2022 15:26:08 +0800 Subject: [PATCH 08/17] Added physics system (untested) --- .../src/Application/SBApplication.cpp | 2 +- SHADE_Application/src/Scenes/SBTestScene.cpp | 88 ++-- .../src/Math/Geometry/SHBoundingBox.cpp | 2 +- .../src/Math/Geometry/SHBoundingBox.h | 14 +- SHADE_Engine/src/Math/Geometry/SHShape.h | 4 +- .../Math/Transform/SHTransformComponent.cpp | 6 +- .../src/Math/Transform/SHTransformComponent.h | 1 + .../Components/SHColliderComponent.cpp | 98 ++++ .../Physics/Components/SHColliderComponent.h | 94 ++++ .../Components/SHRigidBodyComponent.cpp | 461 +++++++---------- .../Physics/Components/SHRigidBodyComponent.h | 111 +++-- SHADE_Engine/src/Physics/SHCollider.cpp | 215 ++++++++ SHADE_Engine/src/Physics/SHCollider.h | 108 ++++ SHADE_Engine/src/Physics/SHPhysicsObject.cpp | 36 +- SHADE_Engine/src/Physics/SHPhysicsObject.h | 37 +- SHADE_Engine/src/Physics/SHPhysicsSystem.cpp | 470 ++++++++++++------ SHADE_Engine/src/Physics/SHPhysicsSystem.h | 86 ++-- 17 files changed, 1193 insertions(+), 640 deletions(-) create mode 100644 SHADE_Engine/src/Physics/Components/SHColliderComponent.cpp create mode 100644 SHADE_Engine/src/Physics/Components/SHColliderComponent.h create mode 100644 SHADE_Engine/src/Physics/SHCollider.cpp create mode 100644 SHADE_Engine/src/Physics/SHCollider.h diff --git a/SHADE_Application/src/Application/SBApplication.cpp b/SHADE_Application/src/Application/SBApplication.cpp index 57e14d71..acad9e14 100644 --- a/SHADE_Application/src/Application/SBApplication.cpp +++ b/SHADE_Application/src/Application/SBApplication.cpp @@ -90,7 +90,7 @@ namespace Sandbox SHADE::SHSystemManager::RegisterRoutine(); SHADE::SHSystemManager::RegisterRoutine(); - //SHADE::SHComponentManager::CreateComponentSparseSet(); + SHADE::SHComponentManager::CreateComponentSparseSet(); SHADE::SHComponentManager::CreateComponentSparseSet(); SHADE::SHComponentManager::CreateComponentSparseSet(); diff --git a/SHADE_Application/src/Scenes/SBTestScene.cpp b/SHADE_Application/src/Scenes/SBTestScene.cpp index 664497df..556ff3ac 100644 --- a/SHADE_Application/src/Scenes/SBTestScene.cpp +++ b/SHADE_Application/src/Scenes/SBTestScene.cpp @@ -18,9 +18,9 @@ using namespace SHADE; namespace Sandbox { - void SBTestScene::WindowFocusFunc([[maybe_unused]]void* window, int focused) + void SBTestScene::WindowFocusFunc([[maybe_unused]] void* window, int focused) { - if(focused) + if (focused) { } else @@ -44,15 +44,15 @@ namespace Sandbox { if (mesh.meshName == "Cube.012") { - handles.push_back(graphicsSystem->AddMesh( - mesh.header.vertexCount, - mesh.vertexPosition.data(), - mesh.texCoords.data(), - mesh.vertexTangent.data(), - mesh.vertexNormal.data(), - mesh.header.indexCount, - mesh.indices.data() - )); + handles.push_back(graphicsSystem->AddMesh( + mesh.header.vertexCount, + mesh.vertexPosition.data(), + mesh.texCoords.data(), + mesh.vertexTangent.data(), + mesh.vertexNormal.data(), + mesh.header.indexCount, + mesh.indices.data() + )); } } graphicsSystem->BuildMeshBuffers(); @@ -62,8 +62,8 @@ namespace Sandbox std::vector> texHandles; for (const auto& tex : textures) { - auto texture = graphicsSystem->Add(tex); - texHandles.push_back(texture); + auto texture = graphicsSystem->Add(tex); + texHandles.push_back(texture); } graphicsSystem->BuildTextures(); @@ -79,14 +79,14 @@ namespace Sandbox constexpr int NUM_ROWS = 100; constexpr int NUM_COLS = 100; static const SHVec3 TEST_OBJ_SPACING = { 0.05f, 0.05f, 0.05f }; - static const SHVec3 TEST_OBJ_START_POS = { - (NUM_COLS / 2 * TEST_OBJ_SPACING.x ) + 1.0f, -2.0f, -1.0f }; + static const SHVec3 TEST_OBJ_START_POS = { -(NUM_COLS / 2 * TEST_OBJ_SPACING.x) + 1.0f, -2.0f, -1.0f }; for (int y = 0; y < NUM_ROWS; ++y) - for (int x = 0; x < NUM_COLS; ++x) - { - auto entity = SHEntityManager::CreateEntity(); + for (int x = 0; x < NUM_COLS; ++x) + { + auto entity = SHEntityManager::CreateEntity(); auto& renderable = *SHComponentManager::GetComponent_s(entity); - auto& transform = *SHComponentManager::GetComponent_s(entity); + auto& transform = *SHComponentManager::GetComponent_s(entity); renderable.Mesh = handles.front(); renderable.SetMaterial(customMat); @@ -95,17 +95,17 @@ namespace Sandbox renderable.GetModifiableMaterial()->SetProperty("data.color", SHVec4(1.0f, 0.0f, 0.0f, 1.0f)); //Set initial positions - transform.SetWorldPosition(TEST_OBJ_START_POS + SHVec3{ - x * TEST_OBJ_SPACING.x, - y * TEST_OBJ_SPACING.y, - 0.0f - }); + transform.SetWorldPosition(TEST_OBJ_START_POS + SHVec3{ + x * TEST_OBJ_SPACING.x, + y * TEST_OBJ_SPACING.y, + 0.0f + }); //transform.SetWorldPosition({-1.0f, -1.0f, -1.0f}); //transform.SetWorldRotation(3.14159265f * 1.5f, -3.14159265f / 2.0f, 0.0f); transform.SetLocalScale(TEST_OBJ_SCALE); stressTestObjects.emplace_back(entity); - } + } auto raccoonSpin = SHEntityManager::CreateEntity(); auto& renderable = *SHComponentManager::GetComponent_s(raccoonSpin); @@ -117,8 +117,8 @@ namespace Sandbox renderable.GetModifiableMaterial()->SetProperty("data.alpha", 1.0f); renderable.GetModifiableMaterial()->SetProperty("data.textureIndex", 1); - transform.SetWorldPosition ({-3.0f, -1.0f, -1.0f}); - transform.SetLocalScale({5.0f, 5.0f, 5.0f}); + transform.SetWorldPosition({ -3.0f, -1.0f, -1.0f }); + transform.SetLocalScale({ 5.0f, 5.0f, 5.0f }); //auto entity = SHEntityManager::CreateEntity(); //auto& renderable = *SHComponentManager::GetComponent_s(entity); @@ -137,21 +137,21 @@ namespace Sandbox //testObjRenderable.SetMaterial(matInst); SHADE::SHScriptEngine* scriptEngine = static_cast(SHADE::SHSystemManager::GetSystem()); - scriptEngine->AddScript(raccoonSpin, "RaccoonSpin"); + scriptEngine->AddScript(raccoonSpin, "RaccoonSpin"); - auto raccoonShowcase = SHEntityManager::CreateEntity(); - auto& renderableShowcase = *SHComponentManager::GetComponent_s(raccoonShowcase); - auto& transformShowcase = *SHComponentManager::GetComponent_s(raccoonShowcase); + auto raccoonShowcase = SHEntityManager::CreateEntity(); + auto& renderableShowcase = *SHComponentManager::GetComponent_s(raccoonShowcase); + auto& transformShowcase = *SHComponentManager::GetComponent_s(raccoonShowcase); - renderableShowcase.Mesh = handles.front(); - renderableShowcase.SetMaterial(customMat); - renderableShowcase.GetModifiableMaterial()->SetProperty("data.color", SHVec4(0.0f, 0.0f, 0.0f, 0.0f)); - renderableShowcase.GetModifiableMaterial()->SetProperty("data.alpha", 1.0f); - renderableShowcase.GetModifiableMaterial()->SetProperty("data.textureIndex", 1); + renderableShowcase.Mesh = handles.front(); + renderableShowcase.SetMaterial(customMat); + renderableShowcase.GetModifiableMaterial()->SetProperty("data.color", SHVec4(0.0f, 0.0f, 0.0f, 0.0f)); + renderableShowcase.GetModifiableMaterial()->SetProperty("data.alpha", 1.0f); + renderableShowcase.GetModifiableMaterial()->SetProperty("data.textureIndex", 1); - transformShowcase.SetWorldPosition({ 3.0f, -1.0f, -1.0f }); - transformShowcase.SetLocalScale({ 5.0f, 5.0f, 5.0f }); - scriptEngine->AddScript(raccoonShowcase, "RaccoonShowcase"); + transformShowcase.SetWorldPosition({ 3.0f, -1.0f, -1.0f }); + transformShowcase.SetLocalScale({ 5.0f, 5.0f, 5.0f }); + scriptEngine->AddScript(raccoonShowcase, "RaccoonShowcase"); } void SBTestScene::Update(float dt) @@ -163,19 +163,19 @@ namespace Sandbox //transform.SetWorldPosition({1.0f, 1.0f, -1.0f}); //transform.SetWorldRotation(0.0f, 0.0f + rotation, 0.0f); //rotation += dt * 0.2f; - + // Destroy entity if space is pressed if (GetKeyState(VK_SPACE) & 0x8000) { rotation = 0.0f; - SHADE::SHScriptEngine* scriptEngine = static_cast(SHADE::SHSystemManager::GetSystem()); - scriptEngine->RemoveAllScripts(testObj); + SHADE::SHScriptEngine* scriptEngine = static_cast(SHADE::SHSystemManager::GetSystem()); + scriptEngine->RemoveAllScripts(testObj); } } void SBTestScene::Render() { - + } void SBTestScene::Unload() @@ -186,8 +186,4 @@ namespace Sandbox { //SHSerialization::SerializeScene("resources/scenes/Scene01.SHADE"); } - } - - - diff --git a/SHADE_Engine/src/Math/Geometry/SHBoundingBox.cpp b/SHADE_Engine/src/Math/Geometry/SHBoundingBox.cpp index 44f01a4b..3abcc315 100644 --- a/SHADE_Engine/src/Math/Geometry/SHBoundingBox.cpp +++ b/SHADE_Engine/src/Math/Geometry/SHBoundingBox.cpp @@ -21,7 +21,7 @@ namespace SHADE /* Constructors & Destructor Definitions */ /*-----------------------------------------------------------------------------------*/ - SHBoundingBox::SHBoundingBox(const SHVec3& c, SHVec3& hE) noexcept + SHBoundingBox::SHBoundingBox(const SHVec3& c, const SHVec3& hE) noexcept : SHShape {} , center { c } , halfExtents { hE } diff --git a/SHADE_Engine/src/Math/Geometry/SHBoundingBox.h b/SHADE_Engine/src/Math/Geometry/SHBoundingBox.h index b60c6c29..5041df63 100644 --- a/SHADE_Engine/src/Math/Geometry/SHBoundingBox.h +++ b/SHADE_Engine/src/Math/Geometry/SHBoundingBox.h @@ -27,15 +27,15 @@ namespace SHADE /* Constructors & Destructor */ /*---------------------------------------------------------------------------------*/ - SHBoundingBox (const SHVec3& center, SHVec3& halfExtents) noexcept; - SHBoundingBox (const SHVec3* vertices, size_t numVertices) noexcept; - SHBoundingBox (const SHBoundingBox* boxes, size_t numBoxes) noexcept; + SHBoundingBox (const SHVec3& center, const SHVec3& halfExtents) noexcept; + SHBoundingBox (const SHVec3* vertices, size_t numVertices) noexcept; + SHBoundingBox (const SHBoundingBox* boxes, size_t numBoxes) noexcept; - SHBoundingBox (const SHBoundingBox& rhs) noexcept; - SHBoundingBox (SHBoundingBox&& rhs) noexcept; + SHBoundingBox (const SHBoundingBox& rhs) noexcept; + SHBoundingBox (SHBoundingBox&& rhs) noexcept; - SHBoundingBox& operator= (const SHBoundingBox& rhs) noexcept; - SHBoundingBox& operator= (SHBoundingBox&& rhs) noexcept; + SHBoundingBox& operator= (const SHBoundingBox& rhs) noexcept; + SHBoundingBox& operator= (SHBoundingBox&& rhs) noexcept; /*---------------------------------------------------------------------------------*/ /* Getter Functions */ diff --git a/SHADE_Engine/src/Math/Geometry/SHShape.h b/SHADE_Engine/src/Math/Geometry/SHShape.h index 84b7bbe7..e33ca583 100644 --- a/SHADE_Engine/src/Math/Geometry/SHShape.h +++ b/SHADE_Engine/src/Math/Geometry/SHShape.h @@ -30,7 +30,9 @@ namespace SHADE enum class Type { BOUNDING_BOX - , RAY + , SPHERE + , CAPSULE + , CONVEX_HULL , TRIANGLE , COUNT diff --git a/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp b/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp index 15cd698b..949cfa67 100644 --- a/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp +++ b/SHADE_Engine/src/Math/Transform/SHTransformComponent.cpp @@ -152,7 +152,7 @@ RTTR_REGISTRATION using namespace rttr; registration::class_("Transform Component") - .property("Translate", &SHTransformComponent::GetLocalPosition, &SHTransformComponent::SetLocalPosition) - .property("Rotate", &SHTransformComponent::GetLocalRotation, select_overload(&SHTransformComponent::SetLocalRotation)) - .property("Scale", &SHTransformComponent::GetLocalScale, &SHTransformComponent::SetLocalScale); + .property("Translate" , &SHTransformComponent::GetLocalPosition , &SHTransformComponent::SetLocalPosition ) + .property("Rotate" , &SHTransformComponent::GetLocalRotation , select_overload(&SHTransformComponent::SetLocalRotation) ) + .property("Scale" , &SHTransformComponent::GetLocalScale , &SHTransformComponent::SetLocalScale ); } \ No newline at end of file diff --git a/SHADE_Engine/src/Math/Transform/SHTransformComponent.h b/SHADE_Engine/src/Math/Transform/SHTransformComponent.h index a87b1921..ad355694 100644 --- a/SHADE_Engine/src/Math/Transform/SHTransformComponent.h +++ b/SHADE_Engine/src/Math/Transform/SHTransformComponent.h @@ -13,6 +13,7 @@ #include #include + // Project Headers #include "SH_API.h" #include "ECS_Base/Components/SHComponent.h" diff --git a/SHADE_Engine/src/Physics/Components/SHColliderComponent.cpp b/SHADE_Engine/src/Physics/Components/SHColliderComponent.cpp new file mode 100644 index 00000000..3e1c7aa6 --- /dev/null +++ b/SHADE_Engine/src/Physics/Components/SHColliderComponent.cpp @@ -0,0 +1,98 @@ +/**************************************************************************************** + * \file SHColliderComponent.cpp + * \author Diren D Bharwani, diren.dbharwani, 390002520 + * \brief Implementation for a Collider Component. + * + * \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 + +// Primary Header +#include "SHColliderComponent.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Getter Function Definitions */ + /*-----------------------------------------------------------------------------------*/ + + bool SHColliderComponent::HasChanged() const noexcept + { + return dirty; + } + + const SHVec3& SHColliderComponent::GetPosition() const noexcept + { + return position; + } + + const SHQuaternion& SHColliderComponent::GetOrientation() const noexcept + { + return orientation; + } + + SHVec3 SHColliderComponent::GetRotation() const noexcept + { + return orientation.ToEuler(); + } + + const SHColliderComponent::Colliders& SHColliderComponent::GetColliders() const noexcept + { + return colliders; + } + + SHCollider& SHColliderComponent::GetCollider(int index) noexcept + { + if (index < 0 || static_cast(index) >= colliders.size()) + throw std::invalid_argument("Out-of-range access!"); + + return colliders[index].first; + } + + /*-----------------------------------------------------------------------------------*/ + /* Public Function Member Definitions */ + /*-----------------------------------------------------------------------------------*/ + + void SHColliderComponent::OnCreate() + { + + } + + void SHColliderComponent::OnDestroy() + { + + } + + void SHColliderComponent::AddBoundingBox() noexcept + { + const auto BOX_PAIR = std::make_pair(SHCollider{SHCollider::Type::BOX}, true); + colliders.emplace_back(BOX_PAIR); + } + + void SHColliderComponent::AddSphere() noexcept + { + + } + + void SHColliderComponent::RemoveCollider(int index) noexcept + { + if (index < 0 || static_cast(index) >= colliders.size()) + throw std::invalid_argument("Out-of-range access!"); + + int idx = 0; + auto it = colliders.begin(); + for (; it != colliders.end(); ++it) + { + if (idx == index) + break; + + ++idx; + } + + it = colliders.erase(it); + } + +} // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/Components/SHColliderComponent.h b/SHADE_Engine/src/Physics/Components/SHColliderComponent.h new file mode 100644 index 00000000..aeb3b9e6 --- /dev/null +++ b/SHADE_Engine/src/Physics/Components/SHColliderComponent.h @@ -0,0 +1,94 @@ +/**************************************************************************************** + * \file SHColliderComponent.h + * \author Diren D Bharwani, diren.dbharwani, 390002520 + * \brief Interface for a Collider Component. + * + * \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 "ECS_Base/Components/SHComponent.h" +#include "Physics/SHCollider.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*-----------------------------------------------------------------------------------*/ + + class SH_API SHColliderComponent : public SHComponent + { + private: + /*---------------------------------------------------------------------------------*/ + /* Friends */ + /*---------------------------------------------------------------------------------*/ + + friend class SHPhysicsSystem; + + /*---------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*---------------------------------------------------------------------------------*/ + + using ColliderDirtyPair = std::pair; + using Colliders = std::vector; + + public: + + /*---------------------------------------------------------------------------------*/ + /* Constructors & Destructor */ + /*---------------------------------------------------------------------------------*/ + + SHColliderComponent () noexcept = default; + SHColliderComponent (const SHColliderComponent& rhs) noexcept = default; + SHColliderComponent (SHColliderComponent&& rhs) noexcept = default; + ~SHColliderComponent () override = default; + + /*---------------------------------------------------------------------------------*/ + /* Operator Overloads */ + /*---------------------------------------------------------------------------------*/ + + SHColliderComponent& operator=(const SHColliderComponent& rhs) noexcept = default; + SHColliderComponent& operator=(SHColliderComponent&& rhs) noexcept = default; + + /*---------------------------------------------------------------------------------*/ + /* Getter Functions */ + /*---------------------------------------------------------------------------------*/ + + [[nodiscard]] bool HasChanged () const noexcept; + + [[nodiscard]] const SHVec3& GetPosition () const noexcept; + [[nodiscard]] const SHQuaternion& GetOrientation () const noexcept; + [[nodiscard]] SHVec3 GetRotation () const noexcept; + + [[nodiscard]] const Colliders& GetColliders () const noexcept; + [[nodiscard]] SHCollider& GetCollider (int index) noexcept; + + /*---------------------------------------------------------------------------------*/ + /* Function Members */ + /*---------------------------------------------------------------------------------*/ + + void OnCreate () override; + void OnDestroy () override; + + void AddBoundingBox () noexcept; + void AddSphere () noexcept; + + void RemoveCollider (int index) noexcept; + + private: + + /*---------------------------------------------------------------------------------*/ + /* Data Members */ + /*---------------------------------------------------------------------------------*/ + + bool dirty; + SHVec3 position; + SHQuaternion orientation; + Colliders colliders; + + }; +} // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp index 16863dbd..04cb00dd 100644 --- a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp +++ b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp @@ -14,9 +14,8 @@ #include "SHRigidBodyComponent.h" // Project Headers -#include "Tools/SHUtilities.h" -#include "Math/SHMathHelpers.h" -#include "Math/SHQuaternion.h" +#include "ECS_Base/Managers/SHSystemManager.h" +#include "Physics/SHPhysicsSystem.h" namespace SHADE { @@ -26,46 +25,32 @@ namespace SHADE SHRigidBodyComponent::SHRigidBodyComponent() noexcept : type { Type::DYNAMIC } + , flags { 0 } + , dirtyFlags { 0 } + , interpolate { true } + , system { nullptr } , mass { 1.0f } , drag { 0.01f } , angularDrag { 0.01f } - , flags { 0 } + { // Set default flags: Gravity & Sleeping enabled flags |= 1U << 0; flags |= 1U << 1; } - SHRigidBodyComponent::~SHRigidBodyComponent() - { - - } - /*-----------------------------------------------------------------------------------*/ /* Getter Function Definitions */ /*-----------------------------------------------------------------------------------*/ bool SHRigidBodyComponent::IsGravityEnabled() const noexcept { - const bool GRAVITY = flags & (1U << 0); - if (rp3dBody) - { - - SHASSERT(reinterpret_cast(rp3dBody)->isGravityEnabled() == GRAVITY, "ReactPhysics and SHADE body enable gravity do not match!") - } - - return GRAVITY; + return flags & (1U << 0); } - bool SHRigidBodyComponent::IsSleepingEnabled() const noexcept + bool SHRigidBodyComponent::IsAllowedToSleep() const noexcept { - const bool SLEEP = flags & (1U << 1); - if (rp3dBody) - { - SHASSERT(reinterpret_cast(rp3dBody)->isAllowedToSleep() == SLEEP, "ReactPhysics and SHADE body enable sleep do not match!") - } - - return SLEEP; + return flags & (1U << 1); } bool SHRigidBodyComponent::IsInterpolating() const noexcept @@ -75,178 +60,87 @@ namespace SHADE SHRigidBodyComponent::Type SHRigidBodyComponent::GetType() const noexcept { - if (rp3dBody) - { - SHASSERT - ( - SHUtilities::ConvertEnum(reinterpret_cast(rp3dBody)->getType()) == SHUtilities::ConvertEnum(type), - "ReactPhysics and SHADE body types do not match!" - ) - } - return type; } float SHRigidBodyComponent::GetMass() const noexcept { - if (rp3dBody) - { - SHASSERT(reinterpret_cast(rp3dBody)->getMass() == mass, "ReactPhysics and SHADE body masses do not match!") - } - return mass; } float SHRigidBodyComponent::GetDrag() const noexcept { - if (rp3dBody) - { - SHASSERT - ( - SHMath::CompareFloat(reinterpret_cast(rp3dBody)->getLinearDamping(), drag), - "ReactPhysics and SADE body drag coefficients do not match!" - ) - } - return drag; } float SHRigidBodyComponent::GetAngularDrag() const noexcept { - if (rp3dBody) - { - SHASSERT - ( - SHMath::CompareFloat(reinterpret_cast(rp3dBody)->getAngularDamping(), angularDrag), - "ReactPhysics and SADE body drag coefficients do not match!" - ) - } - return angularDrag; } bool SHRigidBodyComponent::GetFreezePositionX() const noexcept { - const bool FREEZE_X_POS = flags & (1U << 2); - if (rp3dBody) - { - const bool RP3D_FREEZE_X_POS = fabs(reinterpret_cast(rp3dBody)->getLinearLockAxisFactor().x) > 0.0f; - SHASSERT(RP3D_FREEZE_X_POS == FREEZE_X_POS, "ReactPhysics and SHADE body x-axis position lock do not match!") - } - - return FREEZE_X_POS; + return flags & (1U << 2); } bool SHRigidBodyComponent::GetFreezePositionY() const noexcept { - const bool FREEZE_Y_POS = flags & (1U << 3); - if (rp3dBody) - { - const bool RP3D_FREEZE_Y_POS = fabs(reinterpret_cast(rp3dBody)->getLinearLockAxisFactor().y) > 0.0f; - SHASSERT(RP3D_FREEZE_Y_POS == FREEZE_Y_POS, "ReactPhysics and SHADE body y-axis position lock do not match!") - } - - return FREEZE_Y_POS; + return flags & (1U << 3); } bool SHRigidBodyComponent::GetFreezePositionZ() const noexcept { - const bool FREEZE_Z_POS = flags & (1U << 4); - if (rp3dBody) - { - const bool RP3D_FREEZE_Z_POS = fabs(reinterpret_cast(rp3dBody)->getLinearLockAxisFactor().z) > 0.0f; - SHASSERT(RP3D_FREEZE_Z_POS == FREEZE_Z_POS, "ReactPhysics and SHADE body z-axis position lock do not match!") - } - - return FREEZE_Z_POS; + return flags & (1U << 4); } bool SHRigidBodyComponent::GetFreezeRotationX() const noexcept { - const bool FREEZE_X_ROT = flags & (1U << 5); - if (rp3dBody) - { - const bool RP3D_FREEZE_Y_ROT = fabs(reinterpret_cast(rp3dBody)->getAngularLockAxisFactor().x) > 0.0f; - SHASSERT(RP3D_FREEZE_Y_ROT == FREEZE_X_ROT, "ReactPhysics and SHADE body x-axis rotation lock do not match!") - } - - return FREEZE_X_ROT; + return flags & (1U << 5); } bool SHRigidBodyComponent::GetFreezeRotationY() const noexcept { - const bool FREEZE_Y_ROT = flags & (1U << 6); - if (rp3dBody) - { - const bool RP3D_FREEZE_Y_ROT = fabs(reinterpret_cast(rp3dBody)->getAngularLockAxisFactor().y) > 0.0f; - SHASSERT(RP3D_FREEZE_Y_ROT == FREEZE_Y_ROT, "ReactPhysics and SHADE body y-axis rotation lock do not match!") - } - - return FREEZE_Y_ROT; + return flags & (1U << 6); } bool SHRigidBodyComponent::GetFreezeRotationZ() const noexcept { - const bool FREEZE_Z_ROT = flags & (1U << 7); - if (rp3dBody) - { - const bool RP3D_FREEZE_Z_ROT = fabs(reinterpret_cast(rp3dBody)->getAngularLockAxisFactor().z) > 0.0f; - SHASSERT(RP3D_FREEZE_Z_ROT == FREEZE_Z_ROT, "ReactPhysics and SHADE body z-axis rotation lock do not match!") - } - - return FREEZE_Z_ROT; + return flags & (1U << 7); } - SHVec3 SHRigidBodyComponent::GetForce() const noexcept + const SHVec3& SHRigidBodyComponent::GetForce() const noexcept { - SHVec3 result; - - if (rp3dBody) - { - const auto& RP3D_RESULT = reinterpret_cast(rp3dBody)->getForce(); - result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z }; - } - - return result; + return force; } - SHVec3 SHRigidBodyComponent::GetTorque() const noexcept + const SHVec3& SHRigidBodyComponent::GetTorque() const noexcept { - SHVec3 result; - - if (rp3dBody) - { - const auto& RP3D_RESULT = reinterpret_cast(rp3dBody)->getTorque(); - result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z }; - } - - return result; + return torque; } - SHVec3 SHRigidBodyComponent::GetLinearVelocity() const noexcept + const SHVec3& SHRigidBodyComponent::GetLinearVelocity() const noexcept { - SHVec3 result; - - if (rp3dBody) - { - const auto& RP3D_RESULT = reinterpret_cast(rp3dBody)->getLinearVelocity(); - result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z }; - } - - return result; + return linearVelocity; } - SHVec3 SHRigidBodyComponent::GetAngularVelocity() const noexcept + const SHVec3& SHRigidBodyComponent::GetAngularVelocity() const noexcept { - SHVec3 result; + return angularVelocity; + } - if (rp3dBody) - { - const auto& RP3D_RESULT = reinterpret_cast(rp3dBody)->getAngularVelocity(); - result = SHVec3{ RP3D_RESULT.x, RP3D_RESULT.y, RP3D_RESULT.z }; - } + const SHVec3& SHRigidBodyComponent::GetPosition() const noexcept + { + return position; + } - return result; + const SHQuaternion& SHRigidBodyComponent::GetOrientation() const noexcept + { + return orientation; + } + + SHVec3 SHRigidBodyComponent::GetRotation() const noexcept + { + return orientation.ToEuler(); } /*-----------------------------------------------------------------------------------*/ @@ -258,80 +152,72 @@ namespace SHADE if (type == newType) return; + dirtyFlags |= 1U << 4; type = newType; - if (rp3dBody) - reinterpret_cast(rp3dBody)->setType(static_cast(newType)); - } - - void SHRigidBodyComponent::SetMass(float newMass) noexcept - { - mass = newMass; - if (rp3dBody) - reinterpret_cast(rp3dBody)->setMass(newMass); - } - - void SHRigidBodyComponent::SetDrag(float newDrag) noexcept - { - drag = newDrag; - if (rp3dBody) - reinterpret_cast(rp3dBody)->setLinearDamping(newDrag); - } - - void SHRigidBodyComponent::SetAngularDrag(float newAngularDrag) noexcept - { - angularDrag = newAngularDrag; - if (rp3dBody) - reinterpret_cast(rp3dBody)->setAngularDamping(newAngularDrag); } void SHRigidBodyComponent::SetGravityEnabled(bool enableGravity) noexcept { - SetFlag(enableGravity, 0); - if (rp3dBody) - reinterpret_cast(rp3dBody)->enableGravity(enableGravity); + constexpr int FLAG_POS = 0; + + dirtyFlags |= 1U << FLAG_POS; + enableGravity ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS); } - void SHRigidBodyComponent::SetSleepingEnabled(bool enableSleeping) noexcept + void SHRigidBodyComponent::SetIsAllowedToSleep(bool isAllowedToSleep) noexcept { - SetFlag(enableSleeping, 1); - if (rp3dBody) - reinterpret_cast(rp3dBody)->setIsAllowedToSleep(enableSleeping); + constexpr int FLAG_POS = 1; + + dirtyFlags |= 1U << 1; + isAllowedToSleep ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS); } void SHRigidBodyComponent::SetFreezePositionX(bool freezePositionX) noexcept { - SetFlag(freezePositionX, 2); - SetRP3DLinearConstraints(); + constexpr int FLAG_POS = 2; + + dirtyFlags |= 1U << 2; + freezePositionX ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS); } void SHRigidBodyComponent::SetFreezePositionY(bool freezePositionY) noexcept { - SetFlag(freezePositionY, 3); - SetRP3DLinearConstraints(); + constexpr int FLAG_POS = 3; + + dirtyFlags |= 1U << 2; + freezePositionY ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS); } void SHRigidBodyComponent::SetFreezePositionZ(bool freezePositionZ) noexcept { - SetFlag(freezePositionZ, 4); - SetRP3DLinearConstraints(); + constexpr int FLAG_POS = 4; + + dirtyFlags |= 1U << 2; + freezePositionZ ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS); } void SHRigidBodyComponent::SetFreezeRotationX(bool freezeRotationX) noexcept { - SetFlag(freezeRotationX, 5); - SetRP3DAngularConstraints(); + constexpr int FLAG_POS = 5; + + dirtyFlags |= 1U << 3; + freezeRotationX ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS); } void SHRigidBodyComponent::SetFreezeRotationY(bool freezeRotationY) noexcept { - SetFlag(freezeRotationY, 6); - SetRP3DAngularConstraints(); + constexpr int FLAG_POS = 6; + + dirtyFlags |= 1U << 3; + freezeRotationY ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS); } void SHRigidBodyComponent::SetFreezeRotationZ(bool freezeRotationZ) noexcept { - SetFlag(freezeRotationZ, 7); - SetRP3DAngularConstraints(); + constexpr int FLAG_POS = 7; + + dirtyFlags |= 1U << 3; + freezeRotationZ ? flags |= (1U << FLAG_POS) : flags &= ~(1U << FLAG_POS); } void SHRigidBodyComponent::SetInterpolate(bool allowInterpolation) noexcept @@ -339,22 +225,34 @@ namespace SHADE interpolate = allowInterpolation; } - void SHRigidBodyComponent::SetLinearVelocity(const SHVec3& newLinearVelocity) const noexcept + void SHRigidBodyComponent::SetMass(float newMass) noexcept { - if (rp3dBody) - { - const rp3d::Vector3 NEW_V { newLinearVelocity.x, newLinearVelocity.y, newLinearVelocity.z }; - reinterpret_cast(rp3dBody)->setLinearVelocity(NEW_V); - } + dirtyFlags |= 1U << 5; + mass = newMass; } - void SHRigidBodyComponent::SetAngularVelocity(const SHVec3& newAngularVelocity) const noexcept + void SHRigidBodyComponent::SetDrag(float newDrag) noexcept { - if (rp3dBody) - { - const rp3d::Vector3 NEW_V { newAngularVelocity.x, newAngularVelocity.y, newAngularVelocity.z }; - reinterpret_cast(rp3dBody)->setAngularVelocity(NEW_V); - } + dirtyFlags |= 1U << 6; + drag = newDrag; + } + + void SHRigidBodyComponent::SetAngularDrag(float newAngularDrag) noexcept + { + dirtyFlags |= 1U << 7; + angularDrag = newAngularDrag; + } + + void SHRigidBodyComponent::SetLinearVelocity(const SHVec3& newLinearVelocity) noexcept + { + dirtyFlags |= 1U << 8; + linearVelocity = newLinearVelocity; + } + + void SHRigidBodyComponent::SetAngularVelocity(const SHVec3& newAngularVelocity) noexcept + { + dirtyFlags |= 1U << 9; + angularVelocity = newAngularVelocity; } /*-----------------------------------------------------------------------------------*/ @@ -363,148 +261,143 @@ namespace SHADE void SHRigidBodyComponent::OnCreate() { - componentFlags |= 1U << 0; // dirty - componentFlags |= 1U << 1; // rb dirty - componentFlags |= 1U << 2; // has rb + system = SHSystemManager::GetSystem(); + if (!system) + { + SHLOG_ERROR("Physics system does not exist, Rigid Body Component not added!") + return; + } - Synchronise(); + // Notify Physics System + system->AddRigidBody(GetEID()); } void SHRigidBodyComponent::OnDestroy() { - componentFlags |= 1U << 0; // dirty - componentFlags |= 1U << 1; // rb dirty - componentFlags &= ~(1U << 2); // no rb + // Notify Physics System + if (!system) + { + SHLOG_ERROR("Physics system does not exist, unable to remove Rigid Body Component!") + return; + } - Synchronise(); + system->RemoveRigidBody(GetEID()); } void SHRigidBodyComponent::AddForce(const SHVec3& force) const noexcept { - if (rp3dBody) + if (!system) { - const rp3d::Vector3 F { force.x, force.y, force.z }; - reinterpret_cast(rp3dBody)->applyWorldForceAtCenterOfMass(F); + SHLOG_ERROR("Physics system does not exist, unable to Add Force to a body!") + return; } + + // Notify Physics Systems + system->AddForce(GetEID(), force); } void SHRigidBodyComponent::AddForceAtLocalPos(const SHVec3& force, const SHVec3& localPos) const noexcept { - if (rp3dBody) + if (!system) { - const rp3d::Vector3 F{ force.x, force.y, force.z }; - const rp3d::Vector3 P{ localPos.x, localPos.y, localPos.z }; - reinterpret_cast(rp3dBody)->applyWorldForceAtLocalPosition(F, P); + SHLOG_ERROR("Physics system does not exist, unable to Add Force to a body!") + return; } + + // Notify Physics Systems + system->AddForceAtLocalPos(GetEID(), force, localPos); } void SHRigidBodyComponent::AddForceAtWorldPos(const SHVec3& force, const SHVec3& worldPos) const noexcept { - if (rp3dBody) + if (!system) { - const rp3d::Vector3 F{ force.x, force.y, force.z }; - const rp3d::Vector3 P{ worldPos.x, worldPos.y, worldPos.z }; - reinterpret_cast(rp3dBody)->applyWorldForceAtWorldPosition(F, P); + SHLOG_ERROR("Physics system does not exist, unable to Add Force to a body!") + return; } + + // Notify Physics Systems + system->AddForceAtWorldPos(GetEID(), force, worldPos); } void SHRigidBodyComponent::AddRelativeForce(const SHVec3& relativeForce) const noexcept { - if (rp3dBody) + if (!system) { - const rp3d::Vector3 F{ relativeForce.x, relativeForce.y, relativeForce.z }; - reinterpret_cast(rp3dBody)->applyLocalForceAtCenterOfMass(F); + SHLOG_ERROR("Physics system does not exist, unable to Add Force to a body!") + return; } + + // Notify Physics Systems + system->AddRelativeForce(GetEID(), force); } void SHRigidBodyComponent::AddRelativeForceAtLocalPos(const SHVec3& relativeForce, const SHVec3& localPos) const noexcept { - if (rp3dBody) + if (!system) { - const rp3d::Vector3 F{ relativeForce.x, relativeForce.y, relativeForce.z }; - const rp3d::Vector3 P{ localPos.x, localPos.y, localPos.z }; - reinterpret_cast(rp3dBody)->applyLocalForceAtLocalPosition(F, P); + SHLOG_ERROR("Physics system does not exist, unable to Add Force to a body!") + return; } + + // Notify Physics Systems + system->AddRelativeForceAtLocalPos(GetEID(), force, localPos); } void SHRigidBodyComponent::AddRelativeForceAtWorldPos(const SHVec3& relativeForce, const SHVec3& worldPos) const noexcept { - if (rp3dBody) + if (!system) { - const rp3d::Vector3 F{ relativeForce.x, relativeForce.y, relativeForce.z }; - const rp3d::Vector3 P{ worldPos.x, worldPos.y, worldPos.z }; - reinterpret_cast(rp3dBody)->applyLocalForceAtWorldPosition(F, P); + SHLOG_ERROR("Physics system does not exist, unable to Add Force to a body!") + return; } + + // Notify Physics Systems + system->AddRelativeForceAtWorldPos(GetEID(), force, worldPos); } void SHRigidBodyComponent::AddTorque(const SHVec3& torque) const noexcept { - if (rp3dBody) + if (!system) { - const rp3d::Vector3 T{ torque.x, torque.y, torque.z }; - reinterpret_cast(rp3dBody)->applyWorldTorque(T); + SHLOG_ERROR("Physics system does not exist, unable to Add Force to a body!") + return; } + + // Notify Physics Systems + system->AddTorque(GetEID(), torque); } void SHRigidBodyComponent::AddRelativeTorque(const SHVec3& relativeTorque) const noexcept { - if (rp3dBody) + if (!system) { - const rp3d::Vector3 T{ relativeTorque.x, relativeTorque.y, relativeTorque.z }; - reinterpret_cast(rp3dBody)->applyLocalTorque(T); + SHLOG_ERROR("Physics system does not exist, unable to Add Force to a body!") + return; } + + // Notify Physics Systems + system->AddRelativeTorque(GetEID(), relativeTorque); } - /*-----------------------------------------------------------------------------------*/ - /* Private Function Member Definitions */ - /*-----------------------------------------------------------------------------------*/ +} // namespace SHADE - void SHRigidBodyComponent::SyncRP3DAndSHADE() - { - auto* rigidBody = reinterpret_cast(rp3dBody); +RTTR_REGISTRATION +{ + using namespace SHADE; + using namespace rttr; - rigidBody->setType(static_cast(type)); - - rigidBody->setMass(mass); - rigidBody->setLinearDamping(drag); - rigidBody->setAngularDamping(angularDrag); - - rigidBody->enableGravity(flags & (1U << 0)); - rigidBody->setIsAllowedToSleep(flags & (1U << 1)); - SetRP3DLinearConstraints(); - SetRP3DAngularConstraints(); - } - - - void SHRigidBodyComponent::SetFlag(bool flagState, int flagPos) - { - flagState ? flags |= (1U << flagPos) : flags &= ~(1U << flagPos); - } - - void SHRigidBodyComponent::SetRP3DLinearConstraints() const - { - const rp3d::Vector3 CONSTRAINTS - { - flags & 1U << 2 ? 1.0f : 0.0f, - flags & 1U << 3 ? 1.0f : 0.0f, - flags & 1U << 4 ? 1.0f : 0.0f - }; - - if (rp3dBody) - reinterpret_cast(rp3dBody)->setLinearLockAxisFactor(CONSTRAINTS); - } - - void SHRigidBodyComponent::SetRP3DAngularConstraints() const - { - const rp3d::Vector3 CONSTRAINTS - { - flags & 1U << 5 ? 1.0f : 0.0f, - flags & 1U << 6 ? 1.0f : 0.0f, - flags & 1U << 7 ? 1.0f : 0.0f - }; - - if (rp3dBody) - reinterpret_cast(rp3dBody)->setAngularLockAxisFactor(CONSTRAINTS); - } - -} // namespace SHADE \ No newline at end of file + registration::class_("RigidBody Component") + .property("Type" , &SHRigidBodyComponent::GetType , &SHRigidBodyComponent::SetType ) + .property("Mass" , &SHRigidBodyComponent::GetMass , &SHRigidBodyComponent::SetMass ) + .property("Drag" , &SHRigidBodyComponent::GetDrag , &SHRigidBodyComponent::SetDrag ) + .property("Angular Drag" , &SHRigidBodyComponent::GetAngularDrag , &SHRigidBodyComponent::SetAngularDrag ) + .property("Use Gravity" , &SHRigidBodyComponent::IsGravityEnabled , &SHRigidBodyComponent::SetGravityEnabled ) + .property("Interpolate" , &SHRigidBodyComponent::IsInterpolating , &SHRigidBodyComponent::SetInterpolate ) + .property("Freeze Position X" , &SHRigidBodyComponent::GetFreezePositionX , &SHRigidBodyComponent::SetFreezePositionX ) + .property("Freeze Position Y" , &SHRigidBodyComponent::GetFreezePositionY , &SHRigidBodyComponent::SetFreezePositionY ) + .property("Freeze Position Z" , &SHRigidBodyComponent::GetFreezePositionZ , &SHRigidBodyComponent::SetFreezePositionZ ) + .property("Freeze Rotation X" , &SHRigidBodyComponent::GetFreezeRotationX , &SHRigidBodyComponent::SetFreezeRotationX ) + .property("Freeze Rotation Y" , &SHRigidBodyComponent::GetFreezeRotationY , &SHRigidBodyComponent::SetFreezeRotationY ) + .property("Freeze Rotation Z" , &SHRigidBodyComponent::GetFreezeRotationZ , &SHRigidBodyComponent::SetFreezeRotationZ ); +} \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h index 439fa3db..0793b2ff 100644 --- a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h +++ b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.h @@ -10,6 +10,8 @@ #pragma once +#include + // Project Headers #include "ECS_Base/Components/SHComponent.h" #include "Physics/SHPhysicsObject.h" @@ -20,7 +22,7 @@ namespace SHADE /* Type Definitions */ /*-----------------------------------------------------------------------------------*/ - class SH_API SHRigidBodyComponent : public SHComponent, public SHPhysicsObject + class SH_API SHRigidBodyComponent : public SHComponent { private: /*---------------------------------------------------------------------------------*/ @@ -43,8 +45,6 @@ namespace SHADE , COUNT }; - // TODO(Diren): Collision Types - /*---------------------------------------------------------------------------------*/ /* Constructors & Destructor */ /*---------------------------------------------------------------------------------*/ @@ -52,7 +52,7 @@ namespace SHADE SHRigidBodyComponent () noexcept; SHRigidBodyComponent (const SHRigidBodyComponent& rhs) noexcept = default; SHRigidBodyComponent (SHRigidBodyComponent&& rhs) noexcept = default; - ~SHRigidBodyComponent () override; + ~SHRigidBodyComponent () override = default; /*---------------------------------------------------------------------------------*/ /* Operator Overloads */ @@ -65,56 +65,61 @@ namespace SHADE /* Getter Functions */ /*---------------------------------------------------------------------------------*/ - [[nodiscard]] bool IsGravityEnabled () const noexcept; - [[nodiscard]] bool IsSleepingEnabled () const noexcept; - [[nodiscard]] bool IsInterpolating () const noexcept; + [[nodiscard]] bool IsGravityEnabled () const noexcept; + [[nodiscard]] bool IsAllowedToSleep () const noexcept; + [[nodiscard]] bool IsInterpolating () const noexcept; - [[nodiscard]] Type GetType () const noexcept; - [[nodiscard]] float GetMass () const noexcept; - [[nodiscard]] float GetDrag () const noexcept; - [[nodiscard]] float GetAngularDrag () const noexcept; + [[nodiscard]] Type GetType () const noexcept; + [[nodiscard]] float GetMass () const noexcept; + [[nodiscard]] float GetDrag () const noexcept; + [[nodiscard]] float GetAngularDrag () const noexcept; - [[nodiscard]] bool GetFreezePositionX () const noexcept; - [[nodiscard]] bool GetFreezePositionY () const noexcept; - [[nodiscard]] bool GetFreezePositionZ () const noexcept; + [[nodiscard]] bool GetFreezePositionX () const noexcept; + [[nodiscard]] bool GetFreezePositionY () const noexcept; + [[nodiscard]] bool GetFreezePositionZ () const noexcept; - [[nodiscard]] bool GetFreezeRotationX () const noexcept; - [[nodiscard]] bool GetFreezeRotationY () const noexcept; - [[nodiscard]] bool GetFreezeRotationZ () const noexcept; + [[nodiscard]] bool GetFreezeRotationX () const noexcept; + [[nodiscard]] bool GetFreezeRotationY () const noexcept; + [[nodiscard]] bool GetFreezeRotationZ () const noexcept; - [[nodiscard]] SHVec3 GetForce () const noexcept; - [[nodiscard]] SHVec3 GetTorque () const noexcept; - [[nodiscard]] SHVec3 GetLinearVelocity () const noexcept; - [[nodiscard]] SHVec3 GetAngularVelocity () const noexcept; + [[nodiscard]] const SHVec3& GetForce () const noexcept; + [[nodiscard]] const SHVec3& GetTorque () const noexcept; + [[nodiscard]] const SHVec3& GetLinearVelocity () const noexcept; + [[nodiscard]] const SHVec3& GetAngularVelocity () const noexcept; + + [[nodiscard]] const SHVec3& GetPosition () const noexcept; + [[nodiscard]] const SHQuaternion& GetOrientation () const noexcept; + [[nodiscard]] SHVec3 GetRotation () const noexcept; /*---------------------------------------------------------------------------------*/ /* Setter Functions */ /*---------------------------------------------------------------------------------*/ - void SetType (Type newType) noexcept; - void SetMass (float newMass) noexcept; - void SetDrag (float newDrag) noexcept; - void SetAngularDrag (float newAngularDrag) noexcept; + void SetType (Type newType) noexcept; - void SetGravityEnabled (bool enableGravity) noexcept; - void SetSleepingEnabled (bool enableSleeping) noexcept; - void SetFreezePositionX (bool freezePositionX) noexcept; - void SetFreezePositionY (bool freezePositionY) noexcept; - void SetFreezePositionZ (bool freezePositionZ) noexcept; - void SetFreezeRotationX (bool freezeRotationX) noexcept; - void SetFreezeRotationY (bool freezeRotationY) noexcept; - void SetFreezeRotationZ (bool freezeRotationZ) noexcept; - void SetInterpolate (bool allowInterpolation) noexcept; + void SetGravityEnabled (bool enableGravity) noexcept; + void SetIsAllowedToSleep(bool isAllowedToSleep) noexcept; + void SetFreezePositionX (bool freezePositionX) noexcept; + void SetFreezePositionY (bool freezePositionY) noexcept; + void SetFreezePositionZ (bool freezePositionZ) noexcept; + void SetFreezeRotationX (bool freezeRotationX) noexcept; + void SetFreezeRotationY (bool freezeRotationY) noexcept; + void SetFreezeRotationZ (bool freezeRotationZ) noexcept; + void SetInterpolate (bool allowInterpolation) noexcept; - void SetLinearVelocity (const SHVec3& newLinearVelocity) const noexcept; - void SetAngularVelocity (const SHVec3& newAngularVelocity) const noexcept; + void SetMass (float newMass) noexcept; + void SetDrag (float newDrag) noexcept; + void SetAngularDrag (float newAngularDrag) noexcept; + + void SetLinearVelocity (const SHVec3& newLinearVelocity) noexcept; + void SetAngularVelocity (const SHVec3& newAngularVelocity) noexcept; /*---------------------------------------------------------------------------------*/ /* Function Members */ /*---------------------------------------------------------------------------------*/ - void OnCreate () override; - void OnDestroy () override; + void OnCreate () override; + void OnDestroy () override; void AddForce (const SHVec3& force) const noexcept; void AddForceAtLocalPos (const SHVec3& force, const SHVec3& localPos) const noexcept; @@ -134,23 +139,33 @@ namespace SHADE Type type; + // rX rY rZ pX pY pZ slp g + uint8_t flags; + // 0 0 0 0 0 0 aV lV aD d m t ag lc slp g + uint16_t dirtyFlags; + bool interpolate; + + SHPhysicsSystem* system; + float mass; float drag; float angularDrag; - - // rX rY rZ pX pY pZ slp g - uint8_t flags; - bool interpolate; + + SHVec3 force; + SHVec3 linearVelocity; + + SHVec3 torque; + SHVec3 angularVelocity; + + // TODO(Diren): Once quaternions have replaced euler angles in transforms, store it for the rigidbody. + + SHVec3 position; + SHQuaternion orientation; /*---------------------------------------------------------------------------------*/ /* Function Members */ /*---------------------------------------------------------------------------------*/ - void SyncRP3DAndSHADE (); - void SetFlag (bool flagState, int flagPos); - void SetRP3DLinearConstraints () const ; - void SetRP3DAngularConstraints () const ; - - + RTTR_ENABLE() }; } // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHCollider.cpp b/SHADE_Engine/src/Physics/SHCollider.cpp new file mode 100644 index 00000000..724db19c --- /dev/null +++ b/SHADE_Engine/src/Physics/SHCollider.cpp @@ -0,0 +1,215 @@ +/**************************************************************************************** + * \file SHCollider.cpp + * \author Diren D Bharwani, diren.dbharwani, 390002520 + * \brief Implementation for a Collider. + * + * \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 + +// Primary Header +#include "SHCollider.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Constructors & Destructor Definitions */ + /*-----------------------------------------------------------------------------------*/ + + SHCollider::SHCollider(Type colliderType) + : type { colliderType } + , isTrigger { false } + , dirty { true } + , shape { nullptr } + { + CreateShape(); + } + + SHCollider::SHCollider(const SHCollider& rhs) noexcept + : type { rhs.type} + , isTrigger { rhs.isTrigger } + , dirty { true } + , shape { nullptr } + { + CreateShape(); + + // TODO(Diren): Copy transform data over + } + + SHCollider::SHCollider(SHCollider&& rhs) noexcept + : type { rhs.type} + , isTrigger { rhs.isTrigger } + , dirty { true } + , shape { nullptr } + { + CreateShape(); + + // TODO(Diren): Copy transform data over + } + + SHCollider::~SHCollider() noexcept + { + delete shape; + } + + /*-----------------------------------------------------------------------------------*/ + /* Operator Overload Definitions */ + /*-----------------------------------------------------------------------------------*/ + + SHCollider& SHCollider::operator=(const SHCollider& rhs) noexcept + { + type = rhs.type; + isTrigger = rhs.isTrigger; + dirty = true; + + CreateShape(); + + // TODO(Diren): Copy transform data over + + return *this; + } + + SHCollider& SHCollider::operator=(SHCollider&& rhs) noexcept + { + type = rhs.type; + isTrigger = rhs.isTrigger; + dirty = true; + + CreateShape(); + + // TODO(Diren): Copy transform data over + + return *this; + } + + /*-----------------------------------------------------------------------------------*/ + /* Getter Function Definitions */ + /*-----------------------------------------------------------------------------------*/ + + bool SHCollider::HasChanged() const noexcept + { + return dirty; + } + + bool SHCollider::IsTrigger() const noexcept + { + return isTrigger; + } + + SHCollider::Type SHCollider::GetType() const noexcept + { + return type; + } + + SHShape* SHCollider::GetShape() const noexcept + { + return shape; + } + + float SHCollider::GetFriction() const noexcept + { + // TODO(Diren): Fix after implementing materials + return 0.0f; + } + + float SHCollider::GetBounciness() const noexcept + { + // TODO(Diren): Fix after implementing materials + return 0.0f; + } + float SHCollider::GetDensity() const noexcept + { + // TODO(Diren): Fix after implementing materials + return 0.0f; + } + + SHVec3 SHCollider::GetPosition() const noexcept + { + // TODO(Diren): Fix after linking transform data + return SHVec3::Zero; + } + + const SHVec3& SHCollider::GetPositionOffset() const noexcept + { + return positionOffset; + } + + SHQuaternion SHCollider::GetOrientation() const noexcept + { + // TODO(Diren): Fix after linking transform data + return SHQuaternion::Identity; + } + + /*-----------------------------------------------------------------------------------*/ + /* Setter Function Definitions */ + /*-----------------------------------------------------------------------------------*/ + + void SHCollider::SetType(Type newType) noexcept + { + if (type == newType) + return; + + dirty = true; + + type = newType; + CreateShape(); + } + + void SHCollider::SetIsTrigger(bool trigger) noexcept + { + dirty = true; + isTrigger = trigger; + } + + void SHCollider::SetFriction(float friction) noexcept + { + dirty = true; + } + + void SHCollider::SetBounciness(float bounciness) noexcept + { + dirty = true; + } + + void SHCollider::SetDensity(float density) noexcept + { + dirty = true; + } + + void SHCollider::SetPositionOffset(const SHVec3& posOffset) noexcept + { + dirty = true; + positionOffset = posOffset; + } + + /*-----------------------------------------------------------------------------------*/ + /* Private Member Function Definitions */ + /*-----------------------------------------------------------------------------------*/ + + void SHCollider::CreateShape() + { + // Remove current shape + delete shape; + + switch (type) + { + case Type::BOX: CreateBoundingBox(); break; + case Type::SPHERE: CreateSphere(); break; + default: break; + } + } + + void SHCollider::CreateBoundingBox() + { + shape = new SHBoundingBox{ SHVec3::Zero, SHVec3::One }; + } + + void SHCollider::CreateSphere() + { + + } + +} // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHCollider.h b/SHADE_Engine/src/Physics/SHCollider.h new file mode 100644 index 00000000..fce4a5b2 --- /dev/null +++ b/SHADE_Engine/src/Physics/SHCollider.h @@ -0,0 +1,108 @@ +/**************************************************************************************** + * \file SHCollider.h + * \author Diren D Bharwani, diren.dbharwani, 390002520 + * \brief Interface for a Collider. + * + * \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 "Math/Geometry/SHBoundingBox.h" +#include "Math/SHQuaternion.h" + +namespace SHADE +{ + /*-----------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*-----------------------------------------------------------------------------------*/ + + class SH_API SHCollider + { + public: + /*---------------------------------------------------------------------------------*/ + /* Type Definitions */ + /*---------------------------------------------------------------------------------*/ + + enum class Type + { + BOX + , SPHERE + , CAPSULE + , CONVEX_HULL + , CONVEX_MESH + }; + + /*---------------------------------------------------------------------------------*/ + /* Constructors & Destructor */ + /*---------------------------------------------------------------------------------*/ + + SHCollider (Type colliderType); + + SHCollider (const SHCollider& rhs) noexcept; + SHCollider (SHCollider&& rhs) noexcept; + ~SHCollider () noexcept; + + /*---------------------------------------------------------------------------------*/ + /* Operator Overloads */ + /*---------------------------------------------------------------------------------*/ + + SHCollider& operator=(const SHCollider& rhs) noexcept; + SHCollider& operator=(SHCollider&& rhs) noexcept; + + /*---------------------------------------------------------------------------------*/ + /* Getter Functions */ + /*---------------------------------------------------------------------------------*/ + + [[nodiscard]] bool HasChanged () const noexcept; + + [[nodiscard]] bool IsTrigger () const noexcept; + + [[nodiscard]] Type GetType () const noexcept; + [[nodiscard]] SHShape* GetShape () const noexcept; + + [[nodiscard]] float GetFriction () const noexcept; + [[nodiscard]] float GetBounciness () const noexcept; + [[nodiscard]] float GetDensity () const noexcept; + + [[nodiscard]] SHVec3 GetPosition () const noexcept; + [[nodiscard]] const SHVec3& GetPositionOffset () const noexcept; + [[nodiscard]] SHQuaternion GetOrientation () const noexcept; + + /*---------------------------------------------------------------------------------*/ + /* Setter Functions */ + /*---------------------------------------------------------------------------------*/ + + void SetType (Type newType) noexcept; + + void SetIsTrigger (bool isTrigger) noexcept; + void SetFriction (float friction) noexcept; + void SetBounciness (float bounciness) noexcept; + void SetDensity (float density) noexcept; + + void SetPositionOffset (const SHVec3& positionOffset) noexcept; + + private: + /*---------------------------------------------------------------------------------*/ + /* Data Members */ + /*---------------------------------------------------------------------------------*/ + + Type type; + bool isTrigger; + bool dirty; + SHShape* shape; + SHVec3 positionOffset; + + /*---------------------------------------------------------------------------------*/ + /* Function Members */ + /*---------------------------------------------------------------------------------*/ + + void CreateShape (); + void CreateBoundingBox (); + void CreateSphere (); + }; + +} // namespace SHADE diff --git a/SHADE_Engine/src/Physics/SHPhysicsObject.cpp b/SHADE_Engine/src/Physics/SHPhysicsObject.cpp index 4f0616f8..325d860f 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsObject.cpp +++ b/SHADE_Engine/src/Physics/SHPhysicsObject.cpp @@ -24,9 +24,10 @@ namespace SHADE /*-----------------------------------------------------------------------------------*/ SHPhysicsObject::SHPhysicsObject() noexcept - : entityID { MAX_EID } - , componentFlags { 0 } - , rp3dBody { nullptr } + : entityID { MAX_EID } + , isRigidBody { false } + , hasColliders{ false } + , rp3dBody { nullptr } {} SHPhysicsObject::~SHPhysicsObject() noexcept @@ -81,32 +82,11 @@ namespace SHADE /* Public Function Member Definitions */ /*-----------------------------------------------------------------------------------*/ - void SHPhysicsObject::Synchronise() const - { - if (const bool IS_DIRTY = componentFlags & 1U << 0; IS_DIRTY) - { - auto* physicsSystem = SHSystemManager::GetSystem(); - const bool IS_RIGIDBODY_DIRTY = componentFlags & 1U << 1; - const bool IS_COLLIDER_DIRTY = componentFlags & 1U << 3; - - if (IS_RIGIDBODY_DIRTY) - { - static constexpr auto COMP_ENUM = SHPhysicsSystem::UpdateComponent::RIGID_BODY; - - const bool HAS_RIGIDBODY = componentFlags & 1U << 2; - HAS_RIGIDBODY ? physicsSystem->AddComponent(COMP_ENUM, entityID) : physicsSystem->RemoveComponent(COMP_ENUM, entityID); - } - - if (IS_COLLIDER_DIRTY) - { - static constexpr auto COMP_ENUM = SHPhysicsSystem::UpdateComponent::COLLIDER; - - const bool HAS_COLLIDER = componentFlags & 1U << 2; - HAS_COLLIDER ? physicsSystem->AddComponent(COMP_ENUM, entityID) : physicsSystem->RemoveComponent(COMP_ENUM, entityID); - } - } - } + /*-----------------------------------------------------------------------------------*/ + /* Private Function Member Definitions */ + /*-----------------------------------------------------------------------------------*/ + } // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHPhysicsObject.h b/SHADE_Engine/src/Physics/SHPhysicsObject.h index 20449f2d..e0f0f38f 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsObject.h +++ b/SHADE_Engine/src/Physics/SHPhysicsObject.h @@ -25,22 +25,24 @@ namespace SHADE class SH_API SHPhysicsObject { - protected: + private: /*---------------------------------------------------------------------------------*/ /* Friends */ /*---------------------------------------------------------------------------------*/ friend class SHPhysicsSystem; + friend class SHRigidBodyComponent; + friend class SHColliderComponent; public: /*---------------------------------------------------------------------------------*/ /* Constructors & Destructor */ /*---------------------------------------------------------------------------------*/ - SHPhysicsObject () noexcept; - SHPhysicsObject (const SHPhysicsObject& rhs) noexcept = default; - SHPhysicsObject (SHPhysicsObject&& rhs) noexcept = default; - ~SHPhysicsObject () noexcept; + SHPhysicsObject () noexcept; + SHPhysicsObject (const SHPhysicsObject& rhs) noexcept = default; + SHPhysicsObject (SHPhysicsObject&& rhs) noexcept = default; + virtual ~SHPhysicsObject () noexcept; /*---------------------------------------------------------------------------------*/ /* Operator Overloads */ @@ -53,30 +55,31 @@ namespace SHADE /* Getter Functions */ /*---------------------------------------------------------------------------------*/ - [[nodiscard]] SHVec3 GetPosition () const noexcept; - [[nodiscard]] SHQuaternion GetOrientation () const noexcept; - [[nodiscard]] SHVec3 GetRotation () const noexcept; + [[nodiscard]] virtual SHVec3 GetPosition () const noexcept; + [[nodiscard]] virtual SHQuaternion GetOrientation () const noexcept; + [[nodiscard]] virtual SHVec3 GetRotation () const noexcept; /*---------------------------------------------------------------------------------*/ /* Function Members */ /*---------------------------------------------------------------------------------*/ - /** - * @brief Checks for updates in the component states and tells the physics system to - * make any necessary additions / removals to rp3d side to sync with the SHADE - * component. - */ - void Synchronise() const; - - protected: + private: /*---------------------------------------------------------------------------------*/ /* Data Members */ /*---------------------------------------------------------------------------------*/ EntityID entityID; - uint8_t componentFlags; // 0 0 0 c cDirty rb rbDirty dirty + bool isRigidBody; + bool hasColliders; + rp3d::CollisionBody* rp3dBody; // Can be either a collision body or a rigid body rp3d::Transform prevTransform; // Cached transform for interpolation + /*---------------------------------------------------------------------------------*/ + /* Function Members */ + /*---------------------------------------------------------------------------------*/ + + + }; } // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp b/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp index df69ad04..9be8a5ef 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp +++ b/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp @@ -26,9 +26,9 @@ namespace SHADE /*-----------------------------------------------------------------------------------*/ SHPhysicsSystem::SHPhysicsSystem() - : accumulatedTime { 0.0 } - , fixedDT { 1.0 / 60.0 } - , world { nullptr } + : interpolationFactor { 0.0 } + , fixedDT { 1.0 / 60.0 } + , world { nullptr } {} SHPhysicsSystem::PhysicsPreUpdate::PhysicsPreUpdate() @@ -36,17 +36,22 @@ namespace SHADE {} SHPhysicsSystem::PhysicsFixedUpdate::PhysicsFixedUpdate() - : SHFixedSystemRoutine { DEFAULT_FIXED_STEP, "Physics FixedUpdate", true } + : SHFixedSystemRoutine { DEFAULT_FIXED_STEP, "Physics FixedUpdate", false } {} SHPhysicsSystem::PhysicsPostUpdate::PhysicsPostUpdate() - : SHSystemRoutine { "Physics PostUpdate", true } + : SHSystemRoutine { "Physics PostUpdate", false } {} /*-----------------------------------------------------------------------------------*/ /* Getter Function Definitions */ /*-----------------------------------------------------------------------------------*/ + double SHPhysicsSystem::GetFixedDT() const noexcept + { + return fixedDT; + } + bool SHPhysicsSystem::IsSleepingEnabled() const noexcept { if (world) @@ -97,6 +102,11 @@ namespace SHADE /* Setter Function Definitions */ /*-----------------------------------------------------------------------------------*/ + void SHPhysicsSystem::SetFixedDT(double fixedUpdateRate) noexcept + { + fixedDT = fixedUpdateRate; + } + void SHPhysicsSystem::SetWorldGravity(const SHVec3& gravity) const noexcept { if (world) @@ -185,228 +195,362 @@ namespace SHADE factory.destroyPhysicsWorld(world); } - void SHPhysicsSystem::PhysicsPreUpdate::Execute([[maybe_unused]]double dt) noexcept + void SHPhysicsSystem::AddRigidBody(EntityID entityID) noexcept + { + #ifdef _DEBUG + SHLOG_INFO("Adding a Rigidbody to the Physics World.") + #endif + + // Check if entity is already a physics object + auto* physicsObject = GetPhysicsObject(entityID); + if (!physicsObject) + physicsObject = &(map.emplace(entityID, SHPhysicsObject{}).first->second); + + // Get entity transform + auto const* SHADE_TF = SHComponentManager::GetComponent_s(entityID); + + // Possibly redundant + if (!SHADE_TF) + { + SHComponentManager::AddComponent(entityID); + SHADE_TF = SHComponentManager::GetComponent(entityID); + } + + const SHVec3& SHADE_POS = SHADE_TF->GetWorldPosition(); + const SHVec3& SHADE_ROT = SHADE_TF->GetWorldRotation(); + + const rp3d::Vector3 RP3D_POS { SHADE_POS.x, SHADE_POS.y, SHADE_POS.z }; + const rp3d::Quaternion RP3D_ROT = rp3d::Quaternion::fromEulerAngles( SHADE_ROT.x, SHADE_ROT.y, SHADE_ROT.z ); + + physicsObject->rp3dBody = world->createRigidBody(rp3d::Transform{ RP3D_POS, RP3D_ROT }); + physicsObject->isRigidBody = true; + } + + void SHPhysicsSystem::AddCollider(EntityID entityID) noexcept + { + #ifdef _DEBUG + SHLOG_INFO("Adding a Collider to the Physics World.") + #endif + } + + void SHPhysicsSystem::RemoveRigidBody(EntityID entityID) noexcept + { + #ifdef _DEBUG + SHLOG_INFO("Removing a Rigidbody from the Physics World.") + #endif + + } + + void SHPhysicsSystem::RemoveCollider(EntityID entityID) noexcept + { + #ifdef _DEBUG + SHLOG_INFO("Removing a Collider from the Physics World.") + #endif + } + + void SHPhysicsSystem::AddForce(EntityID entityID, const SHVec3& force) const noexcept + { + + } + + void SHPhysicsSystem::AddForceAtLocalPos(EntityID entityID, const SHVec3& force, const SHVec3& localPos) const noexcept + { + + } + + void SHPhysicsSystem::AddForceAtWorldPos(EntityID entityID, const SHVec3& force, const SHVec3& worldPos) const noexcept + { + + } + + void SHPhysicsSystem::AddRelativeForce(EntityID entityID, const SHVec3& relativeForce) const noexcept + { + + } + + void SHPhysicsSystem::AddRelativeForceAtLocalPos(EntityID entityID, const SHVec3& relativeForce, const SHVec3& localPos) const noexcept + { + + } + + void SHPhysicsSystem::AddRelativeForceAtWorldPos(EntityID entityID, const SHVec3& relativeForce, const SHVec3& worldPos) const noexcept + { + + } + + void SHPhysicsSystem::AddTorque(EntityID entityID, const SHVec3& torque) const noexcept + { + + } + + void SHPhysicsSystem::AddRelativeTorque(EntityID entityID, const SHVec3& relativeTorque) const noexcept + { + + } + + void SHPhysicsSystem::PhysicsPreUpdate::Execute(double) noexcept { auto* system = reinterpret_cast(GetSystem()); - system->ClearUpdateQueue(); - //system->SyncActiveStates(SHSceneManager::GetCurrentSceneGraph()); + // Update bodies and colliders if component is dirty + const auto& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); + system->SyncComponents(sceneGraph); } - void SHPhysicsSystem::PhysicsFixedUpdate::FixedExecute(double dt) noexcept + void SHPhysicsSystem::PhysicsFixedUpdate::Execute(double dt) noexcept { auto* system = reinterpret_cast(GetSystem()); - system->world->update(static_cast(dt)); + fixedTimeStep = 1.0 / system->fixedDT; + accumulatedTime += dt; - system->fixedDT = fixedTimeStep; - system->accumulatedTime = accumulatedTime; + int count = 0; + while (accumulatedTime > fixedTimeStep) + { + system->world->update(static_cast(fixedTimeStep)); + + accumulatedTime -= fixedTimeStep; + ++count; + } + + stats.numSteps = count; + + system->interpolationFactor = accumulatedTime / fixedTimeStep; } - void SHPhysicsSystem::PhysicsPostUpdate::Execute(double dt) noexcept + void SHPhysicsSystem::PhysicsPostUpdate::Execute(double) noexcept { auto* system = reinterpret_cast(GetSystem()); // Interpolate transforms for rendering const auto& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); - //system->SyncTransforms(sceneGraph); + system->SyncTransforms(sceneGraph); // TODO(Diren): Handle trigger messages for scripting } - /*-----------------------------------------------------------------------------------*/ - /* Protected Function Member Definitions */ - /*-----------------------------------------------------------------------------------*/ - - void SHPhysicsSystem::AddComponent(UpdateComponent comp, EntityID entityID) noexcept - { - updateQueue.push({ comp, UpdateType::ADD, entityID }); - } - - - void SHPhysicsSystem::RemoveComponent(UpdateComponent comp, EntityID entityID) noexcept - { - updateQueue.push({ comp, UpdateType::REMOVE, entityID }); - } - /*-----------------------------------------------------------------------------------*/ /* Private Function Member Definitions */ /*-----------------------------------------------------------------------------------*/ - void SHPhysicsSystem::ClearUpdateQueue() noexcept + SHPhysicsObject* SHPhysicsSystem::GetPhysicsObject(EntityID entityID) noexcept { - while (!updateQueue.empty()) + const auto it = map.find(entityID); + if (it == map.end()) { - const auto& CMD = updateQueue.front(); - switch (CMD.type) - { - case UpdateType::ADD: - { - switch (CMD.component) - { - case UpdateComponent::RIGID_BODY: AddRigidBody(CMD.entityID); break; - //case UpdateComponent::COLLIDER: AddCollider(CMD.entityID); break; - default: break; - } - } - case UpdateType::REMOVE: - { - switch (CMD.component) - { - case UpdateComponent::RIGID_BODY: RemoveRigidBody(CMD.entityID); break; - //case UpdateComponent::COLLIDER: RemoveCollider(CMD.entityID); break; - default: break; - } - } - default: break; - } - - updateQueue.pop(); + SHLOG_ERROR("Entity {} is not in the physics system!", entityID) + return nullptr; } + + return &(it->second); } - void SHPhysicsSystem::SyncActiveStates(const SHSceneGraph& sceneGraph) const noexcept + void SHPhysicsSystem::SyncComponents(const SHSceneGraph& sceneGraph) noexcept { - // Sync active states: if node or component is not active, set rp3d to inactive - static constexpr auto SYNC_ACTIVE = [](SHSceneNode* node) + static const auto SYNC_COMPONENTS = [&](SHSceneNode* node) { const EntityID ENTITY_ID = node->GetEntityID(); - // Check if has rigid body - auto const* rigidBodyComponent = SHComponentManager::GetComponent_s(ENTITY_ID); - if(rigidBodyComponent) - { - const bool RP3D_ACTIVE = rigidBodyComponent->rp3dBody->isActive(); - const bool SHADE_ACTIVE = node->IsActive() && rigidBodyComponent->isActive; + // Get physics object + auto const* physicsObject = GetPhysicsObject(ENTITY_ID); + if (!physicsObject) + return; - if (RP3D_ACTIVE != SHADE_ACTIVE) - rigidBodyComponent->rp3dBody->setIsActive(SHADE_ACTIVE); - } - else // Check for a collider + const bool RP3D_ACTIVE = physicsObject->rp3dBody->isActive(); + const bool NODE_ACTIVE = node->IsActive(); + + // Sync rigid body + if (physicsObject->isRigidBody) { + auto* rbComponent = SHComponentManager::GetComponent_s(ENTITY_ID); + if (rbComponent->dirtyFlags > 0) + { + SyncRB(physicsObject, rbComponent); + rbComponent->dirtyFlags = 0; + } + + + // Sync active states + const bool SHADE_ACTIVE = NODE_ACTIVE && rbComponent->isActive; + if (SHADE_ACTIVE != RP3D_ACTIVE) + physicsObject->rp3dBody->setIsActive(SHADE_ACTIVE); + } + + // Sync colliders + if (physicsObject->hasColliders) + { + auto const* colliderComponent = SHComponentManager::GetComponent_s(ENTITY_ID); } + + // Sync transforms + auto const* tfComponent = SHComponentManager::GetComponent(ENTITY_ID); + if (tfComponent->HasChanged()) + { + const SHVec3& SHADE_POS = tfComponent->GetWorldPosition(); + const SHVec3& SHADE_ROT = tfComponent->GetWorldRotation(); + + const rp3d::Vector3 RP3D_POS { SHADE_POS.x, SHADE_POS.y, SHADE_POS.z }; + const rp3d::Quaternion RP3D_ROT = rp3d::Quaternion::fromEulerAngles(SHADE_ROT.x, SHADE_ROT.y, SHADE_ROT.z); + + physicsObject->rp3dBody->setTransform(rp3d::Transform{ RP3D_POS, RP3D_ROT }); + } }; - sceneGraph.Traverse(SYNC_ACTIVE); + sceneGraph.Traverse(SYNC_COMPONENTS); } - void SHPhysicsSystem::SyncTransforms(const SHSceneGraph& sceneGraph) const noexcept + void SHPhysicsSystem::SyncTransforms(const SHSceneGraph& sceneGraph) noexcept { - const rp3d::decimal INTERPOLATION_FACTOR = static_cast(accumulatedTime / fixedDT); - static const auto SYNC_TRANSFORMS = [&](SHSceneNode* node) { const EntityID ENTITY_ID = node->GetEntityID(); - // Check if has rigid body - if (auto* rb = SHComponentManager::GetComponent_s(ENTITY_ID); rb) + // Get physics object + auto* physicsObject = GetPhysicsObject(ENTITY_ID); + if (!physicsObject) + return; + + auto* tfComponent = SHComponentManager::GetComponent_s(ENTITY_ID); + + rp3d::Vector3 rp3dPos; + rp3d::Quaternion rp3dRot; + + const rp3d::Transform CURRENT_TF = physicsObject->rp3dBody->getTransform(); + + // Check if transform should be interpolated + auto const* rbComponent = SHComponentManager::GetComponent_s(ENTITY_ID); + if (rbComponent && rbComponent->IsInterpolating()) { - if (node->IsActive() && rb->isActive) - { - // Get SHADE transform - auto* transformComponent = SHComponentManager::GetComponent_s(ENTITY_ID); - SHASSERT(transformComponent != nullptr, "Transform Component missing from Entity " + std::to_string(ENTITY_ID)) + const rp3d::Transform PREV_TF = physicsObject->prevTransform; + const rp3d::Transform INTERPOLATED_TF = rp3d::Transform::interpolateTransforms(PREV_TF, CURRENT_TF, static_cast(interpolationFactor)); - SHVec3 shadePos, shadeRot; - - if (rb->interpolate) - { - const rp3d::Transform CURRENT_TRANSFORM = rb->rp3dBody->getTransform(); - const rp3d::Transform INTERPOLATED_TRANSFORM = rp3d::Transform::interpolateTransforms(rb->prevTransform, CURRENT_TRANSFORM, INTERPOLATION_FACTOR); - - const auto& RP3D_POS = INTERPOLATED_TRANSFORM.getPosition(); - shadePos = SHVec3{ RP3D_POS.x, RP3D_POS.y, RP3D_POS.z }; - - const auto& RP3D_ORT = INTERPOLATED_TRANSFORM.getOrientation(); - shadeRot = SHQuaternion{ RP3D_ORT.x, RP3D_ORT.y, RP3D_ORT.z, RP3D_ORT.w }.ToEuler(); - - rb->prevTransform = CURRENT_TRANSFORM; - } - else - { - - const auto& RP3D_POS = rb->GetPosition(); - shadePos = SHVec3{ RP3D_POS.x, RP3D_POS.y, RP3D_POS.z }; - shadeRot = rb->GetOrientation().ToEuler(); - } - - transformComponent->SetWorldPosition(shadePos); - transformComponent->SetWorldRotation(shadeRot); - } - else // Check for a collider - { - - } + + rp3dPos = INTERPOLATED_TF.getPosition(); + rp3dRot = INTERPOLATED_TF.getOrientation(); } + else + { + rp3dPos = CURRENT_TF.getPosition(); + rp3dRot = CURRENT_TF.getOrientation(); + } + + // Convert RP3D Transform to SHADE + const SHVec3 SHADE_POS = SHVec3{ rp3dPos.x, rp3dPos.y, rp3dPos.z }; + const SHVec3 SHADE_ROT = SHQuaternion{ rp3dRot.x, rp3dRot.y, rp3dRot.z, rp3dRot.w }.ToEuler(); + + tfComponent->SetWorldPosition(SHADE_POS); + tfComponent->SetWorldRotation(SHADE_ROT); + + // Cache transforms + physicsObject->prevTransform = CURRENT_TF; }; sceneGraph.Traverse(SYNC_TRANSFORMS); } - - void SHPhysicsSystem::AddRigidBody(EntityID entityID) const noexcept + void SHPhysicsSystem::SyncRB(SHPhysicsObject const* physicsObject, const SHRigidBodyComponent* comp) noexcept { - #ifdef _DEBUG - SHLOG_INFO("Adding a Rigidbody to the Physics World.") - #endif + auto* rigidBody = reinterpret_cast(physicsObject->rp3dBody); - // Rigid Bodies need a transform. - auto const* transformComponent = SHComponentManager::GetComponent_s(entityID); - if (!transformComponent) + const uint16_t RB_FLAGS = comp->dirtyFlags; + const size_t NUM_FLAGS = sizeof(RB_FLAGS) * 8U; + for (size_t i = 0; i < NUM_FLAGS; ++i) { - // NOTE: This should already be handled by the editor. + // Check if current dirty flag has been set to true + if (RB_FLAGS & 1U << i) + { + switch (i) + { + case 0: // Gravity + { + rigidBody->enableGravity(comp->IsGravityEnabled()); + break; + } + case 1: // Sleeping + { + rigidBody->setIsAllowedToSleep(comp->IsAllowedToSleep()); + break; + } + case 2: // Linear Constraints + { + SetRP3DLinearConstraints(rigidBody, comp->flags); + break; + } + case 3: // Angular Constraints + { + SetRP3DAngularConstraints(rigidBody, comp->flags); + break; + } + case 4: // Type + { + rigidBody->setType(static_cast(comp->GetType())); + break; + } + case 5: // Mass + { + rigidBody->setMass(comp->GetMass()); + break; + } + case 6: // Drag + { + rigidBody->setLinearDamping(comp->GetDrag()); + break; + } + case 7: // Angular Drag + { + rigidBody->setAngularDamping(comp->GetAngularDrag()); + break; + } + case 8: // Linear Velocity + { + const SHVec3& SHADE_VEL = comp->GetLinearVelocity(); + rp3d::Vector3 RP3D_VEL { SHADE_VEL.x, SHADE_VEL.y, SHADE_VEL.z }; - SHLOG_INFO("Automatically adding a transform to Entity {}", entityID) - SHComponentManager::AddComponent(entityID); - transformComponent = SHComponentManager::GetComponent(entityID); + rigidBody->setLinearVelocity(RP3D_VEL); + break; + } + case 9: // Angular Velocity + { + const SHVec3& SHADE_VEL = comp->GetAngularVelocity(); + rp3d::Vector3 RP3D_VEL { SHADE_VEL.x, SHADE_VEL.y, SHADE_VEL.z }; + + rigidBody->setAngularVelocity(RP3D_VEL); + break; + } + default: break; + } + } } - - const SHVec3& SHADE_WORLD_POSITION = transformComponent->GetWorldPosition(); - const rp3d::Vector3 RP3D_POSITION { SHADE_WORLD_POSITION.x, SHADE_WORLD_POSITION.y, SHADE_WORLD_POSITION.z }; - - const SHVec3& SHADE_WORLD_ROTATION = transformComponent->GetWorldRotation(); - const rp3d::Quaternion RP3D_ORIENTATION = rp3d::Quaternion::fromEulerAngles(SHADE_WORLD_ROTATION.x, SHADE_WORLD_ROTATION.y, SHADE_WORLD_ROTATION.z); - - const rp3d::Transform RP3D_TF { RP3D_POSITION, RP3D_ORIENTATION }; - - auto* rigidBodyComponent = SHComponentManager::GetComponent_s(entityID); - if (!rigidBodyComponent) - { - // NOTE: This should already be handled by the editor. - - SHLOG_INFO("Automatically adding a rigidbody to Entity {}", entityID) - SHComponentManager::AddComponent(entityID); - rigidBodyComponent = SHComponentManager::GetComponent(entityID); - } - - rigidBodyComponent->rp3dBody = world->createRigidBody(RP3D_TF); - rigidBodyComponent->prevTransform = RP3D_TF; - rigidBodyComponent->SyncRP3DAndSHADE(); - - // Reassign collider - //if (collider) - //{ - // collider. - //} } - void SHPhysicsSystem::RemoveRigidBody(EntityID entityID) const noexcept + void SHPhysicsSystem::SetRP3DLinearConstraints(rp3d::RigidBody const* rp3dRigidBody, uint8_t rbFlags) noexcept { - #ifdef _DEBUG - SHLOG_INFO("Removing a Rigidbody from the Physics World.") - #endif - - auto* rigidBodyComponent = SHComponentManager::GetComponent_s(entityID); - if (rigidBodyComponent == nullptr) + const rp3d::Vector3 CONSTRAINTS { - SHLOG_ERROR("Entity {} does not have a rigidbody component to remove!", entityID) - return; - } + rbFlags & 1U << 2 ? 1.0f : 0.0f, + rbFlags & 1U << 3 ? 1.0f : 0.0f, + rbFlags & 1U << 4 ? 1.0f : 0.0f + }; - // If a collider exists, remake the colliders with a collision body + + rp3dRigidBody->setLinearLockAxisFactor(CONSTRAINTS); + } - world->destroyRigidBody(reinterpret_cast(rigidBodyComponent->rp3dBody)); - rigidBodyComponent->rp3dBody = nullptr; // this should be redundant + void SHPhysicsSystem::SetRP3DAngularConstraints(rp3d::RigidBody const* rp3dRigidBody, uint8_t rbFlags) noexcept + { + const rp3d::Vector3 CONSTRAINTS + { + rbFlags & 1U << 5 ? 1.0f : 0.0f, + rbFlags & 1U << 6 ? 1.0f : 0.0f, + rbFlags & 1U << 7 ? 1.0f : 0.0f + }; + + rp3dRigidBody->setAngularLockAxisFactor(CONSTRAINTS); + } + + void SHPhysicsSystem::SyncColliders(SHPhysicsObject const* physicsObject, const SHColliderComponent* comp) noexcept + { + } } // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHPhysicsSystem.h b/SHADE_Engine/src/Physics/SHPhysicsSystem.h index 273eb54d..af615f35 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsSystem.h +++ b/SHADE_Engine/src/Physics/SHPhysicsSystem.h @@ -11,16 +11,20 @@ #pragma once #include +#include #include // Project Headers -#include "Math/SHQuaternion.h" +#include "SHPhysicsObject.h" #include "Components/SHRigidBodyComponent.h" +#include "Components/SHColliderComponent.h" + #include "Scene/SHSceneGraph.h" #include "ECS_Base/System/SHSystemRoutine.h" #include "ECS_Base/System/SHFixedSystemRoutine.h" + namespace SHADE { /*-----------------------------------------------------------------------------------*/ @@ -29,13 +33,6 @@ namespace SHADE class SH_API SHPhysicsSystem : public SHSystem { - protected: - /*---------------------------------------------------------------------------------*/ - /* Friends */ - /*---------------------------------------------------------------------------------*/ - - friend class SHPhysicsObject; - public: /*---------------------------------------------------------------------------------*/ /* Type Definitions */ @@ -59,6 +56,8 @@ namespace SHADE /* Getter Functions */ /*---------------------------------------------------------------------------------*/ + [[nodiscard]] double GetFixedDT () const noexcept; + [[nodiscard]] bool IsSleepingEnabled () const noexcept; [[nodiscard]] SHVec3 GetWorldGravity () const noexcept; @@ -70,7 +69,7 @@ namespace SHADE /* Setter Functions */ /*---------------------------------------------------------------------------------*/ - //void SetFixedUpdate (double fixedUpdateRate) noexcept; + void SetFixedDT (double fixedUpdateRate) noexcept; void SetWorldGravity (const SHVec3& gravity) const noexcept; void SetNumberVelocityIterations (uint16_t numVelIterations) const noexcept; void SetNumberPositionIterations (uint16_t numPosIterations) const noexcept; @@ -82,13 +81,32 @@ namespace SHADE /* Function Members */ /*---------------------------------------------------------------------------------*/ - void Init () override; - void Exit () override; + void Init () override; + void Exit () override; + + void AddRigidBody (EntityID entityID) noexcept; + void AddCollider (EntityID entityID) noexcept; + void RemoveRigidBody (EntityID entityID) noexcept; + void RemoveCollider (EntityID entityID) noexcept; + + void AddForce (EntityID entityID, const SHVec3& force) const noexcept; + void AddForceAtLocalPos (EntityID entityID, const SHVec3& force, const SHVec3& localPos) const noexcept; + void AddForceAtWorldPos (EntityID entityID, const SHVec3& force, const SHVec3& worldPos) const noexcept; + + void AddRelativeForce (EntityID entityID, const SHVec3& relativeForce) const noexcept; + void AddRelativeForceAtLocalPos (EntityID entityID, const SHVec3& relativeForce, const SHVec3& localPos) const noexcept; + void AddRelativeForceAtWorldPos (EntityID entityID, const SHVec3& relativeForce, const SHVec3& worldPos) const noexcept; + + void AddTorque (EntityID entityID, const SHVec3& torque) const noexcept; + void AddRelativeTorque (EntityID entityID, const SHVec3& relativeTorque) const noexcept; /*---------------------------------------------------------------------------------*/ /* System Routines */ /*---------------------------------------------------------------------------------*/ + /** + * @brief Synchronises RP3D with SHADE + */ class SH_API PhysicsPreUpdate : public SHSystemRoutine { public: @@ -118,8 +136,7 @@ namespace SHADE /* Function Members */ /*-------------------------------------------------------------------------------*/ - //void Execute (double dt) noexcept override; - void FixedExecute (double dt) noexcept override; + void Execute (double dt) noexcept override; }; class SH_API PhysicsPostUpdate : public SHSystemRoutine @@ -138,56 +155,43 @@ namespace SHADE void Execute(double dt) noexcept override; }; - protected: + private: /*---------------------------------------------------------------------------------*/ /* Type Definitions */ /*---------------------------------------------------------------------------------*/ - enum class UpdateComponent { RIGID_BODY, COLLIDER }; - enum class UpdateType { ADD, REMOVE }; + using EntityObjectMap = std::unordered_map; - struct UpdateCommand - { - UpdateComponent component; - UpdateType type; - EntityID entityID; - }; - - /*---------------------------------------------------------------------------------*/ - /* Function Members */ - /*---------------------------------------------------------------------------------*/ - - void AddComponent (UpdateComponent comp, EntityID entityID) noexcept; - void RemoveComponent (UpdateComponent comp, EntityID entityID) noexcept; - - private: /*---------------------------------------------------------------------------------*/ /* Data Members */ /*---------------------------------------------------------------------------------*/ - // TODO(Diren): Store interpFactor & fixedUpdate for modifiable fixedDT + // TODO(Diren): Store interpFactor - double accumulatedTime; + double interpolationFactor; double fixedDT; rp3d::PhysicsCommon factory; rp3d::PhysicsWorld* world; - std::queue updateQueue; + EntityObjectMap map; + + /*---------------------------------------------------------------------------------*/ /* Function Members */ /*---------------------------------------------------------------------------------*/ + SHPhysicsObject* GetPhysicsObject (EntityID entityID) noexcept; - void ClearUpdateQueue () noexcept; - void SyncActiveStates (const SHSceneGraph& sceneGraph) const noexcept; - void SyncTransforms (const SHSceneGraph& sceneGraph) const noexcept; + void SyncComponents (const SHSceneGraph& sceneGraph) noexcept; + void SyncTransforms (const SHSceneGraph& sceneGraph) noexcept; // TODO(Diren): Trigger handling - void AddRigidBody (EntityID entityID) const noexcept; - void AddCollider (EntityID entityID) const noexcept; - void RemoveRigidBody (EntityID entityID) const noexcept; - void RemoveCollider (EntityID entityID) const noexcept; + static void SyncRB (SHPhysicsObject const* physicsObject, const SHRigidBodyComponent* comp) noexcept; + static void SetRP3DLinearConstraints (rp3d::RigidBody const* rp3dRigidBody, uint8_t rbFlags) noexcept; + static void SetRP3DAngularConstraints (rp3d::RigidBody const* rp3dRigidBody, uint8_t rbFlags) noexcept; + + static void SyncColliders (SHPhysicsObject const* physicsObject, const SHColliderComponent* comp) noexcept; }; From 374f1a961dc3a2e6ad4ef28be6aa7581a74439b6 Mon Sep 17 00:00:00 2001 From: Diren D Bharwani Date: Sat, 1 Oct 2022 16:50:50 +0800 Subject: [PATCH 09/17] Integrated rigidbodies into physics system --- SHADE_Application/src/Scenes/SBTestScene.cpp | 122 ++++++++------- .../Components/SHRigidBodyComponent.cpp | 3 + SHADE_Engine/src/Physics/SHPhysicsObject.cpp | 38 ++++- SHADE_Engine/src/Physics/SHPhysicsObject.h | 12 +- SHADE_Engine/src/Physics/SHPhysicsSystem.cpp | 148 +++++++++--------- SHADE_Engine/src/Physics/SHPhysicsSystem.h | 5 +- 6 files changed, 180 insertions(+), 148 deletions(-) diff --git a/SHADE_Application/src/Scenes/SBTestScene.cpp b/SHADE_Application/src/Scenes/SBTestScene.cpp index 556ff3ac..ce52be95 100644 --- a/SHADE_Application/src/Scenes/SBTestScene.cpp +++ b/SHADE_Application/src/Scenes/SBTestScene.cpp @@ -10,6 +10,7 @@ #include "Scripting/SHScriptEngine.h" #include "Math/Transform/SHTransformComponent.h" #include "Graphics/MiddleEnd/Interface/SHMaterialInstance.h" +#include "Physics/Components/SHRigidBodyComponent.h" #include "Assets/SHAssetManager.h" @@ -75,83 +76,86 @@ namespace Sandbox customMat->SetProperty("data.alpha", 0.1f); // Create Stress Test Objects - static const SHVec3 TEST_OBJ_SCALE = { 0.05f, 0.05f, 0.05f }; - constexpr int NUM_ROWS = 100; - constexpr int NUM_COLS = 100; - static const SHVec3 TEST_OBJ_SPACING = { 0.05f, 0.05f, 0.05f }; - static const SHVec3 TEST_OBJ_START_POS = { -(NUM_COLS / 2 * TEST_OBJ_SPACING.x) + 1.0f, -2.0f, -1.0f }; + //static const SHVec3 TEST_OBJ_SCALE = { 0.05f, 0.05f, 0.05f }; + //constexpr int NUM_ROWS = 100; + //constexpr int NUM_COLS = 100; + //static const SHVec3 TEST_OBJ_SPACING = { 0.05f, 0.05f, 0.05f }; + //static const SHVec3 TEST_OBJ_START_POS = { -(NUM_COLS / 2 * TEST_OBJ_SPACING.x) + 1.0f, -2.0f, -1.0f }; - for (int y = 0; y < NUM_ROWS; ++y) - for (int x = 0; x < NUM_COLS; ++x) - { - auto entity = SHEntityManager::CreateEntity(); - auto& renderable = *SHComponentManager::GetComponent_s(entity); - auto& transform = *SHComponentManager::GetComponent_s(entity); + //for (int y = 0; y < NUM_ROWS; ++y) + // for (int x = 0; x < NUM_COLS; ++x) + // { + // auto entity = SHEntityManager::CreateEntity(); + // auto& renderable = *SHComponentManager::GetComponent_s(entity); + // auto& transform = *SHComponentManager::GetComponent_s(entity); - renderable.Mesh = handles.front(); - renderable.SetMaterial(customMat); + // //renderable.Mesh = handles.front(); + // renderable.Mesh = CUBE_MESH; + // renderable.SetMaterial(customMat); - if (y == 50) - renderable.GetModifiableMaterial()->SetProperty("data.color", SHVec4(1.0f, 0.0f, 0.0f, 1.0f)); + // if (y == 50) + // renderable.GetModifiableMaterial()->SetProperty("data.color", SHVec4(1.0f, 0.0f, 0.0f, 1.0f)); - //Set initial positions - transform.SetWorldPosition(TEST_OBJ_START_POS + SHVec3{ - x * TEST_OBJ_SPACING.x, - y * TEST_OBJ_SPACING.y, - 0.0f - }); - //transform.SetWorldPosition({-1.0f, -1.0f, -1.0f}); - //transform.SetWorldRotation(3.14159265f * 1.5f, -3.14159265f / 2.0f, 0.0f); - transform.SetLocalScale(TEST_OBJ_SCALE); + // //Set initial positions + // transform.SetWorldPosition(TEST_OBJ_START_POS + SHVec3{ + // x * TEST_OBJ_SPACING.x, + // y * TEST_OBJ_SPACING.y, + // 0.0f + // }); + // //transform.SetWorldPosition({-1.0f, -1.0f, -1.0f}); + // //transform.SetWorldRotation(3.14159265f * 1.5f, -3.14159265f / 2.0f, 0.0f); + // transform.SetLocalScale(TEST_OBJ_SCALE); - stressTestObjects.emplace_back(entity); - } + // stressTestObjects.emplace_back(entity); + // } - auto raccoonSpin = SHEntityManager::CreateEntity(); - auto& renderable = *SHComponentManager::GetComponent_s(raccoonSpin); - auto& transform = *SHComponentManager::GetComponent_s(raccoonSpin); + //auto raccoonSpin = SHEntityManager::CreateEntity(); + //auto& renderable = *SHComponentManager::GetComponent_s(raccoonSpin); + //auto& transform = *SHComponentManager::GetComponent_s(raccoonSpin); - renderable.Mesh = handles.front(); - renderable.SetMaterial(customMat); - renderable.GetModifiableMaterial()->SetProperty("data.color", SHVec4(0.0f, 0.0f, 0.0f, 0.0f)); - renderable.GetModifiableMaterial()->SetProperty("data.alpha", 1.0f); - renderable.GetModifiableMaterial()->SetProperty("data.textureIndex", 1); - - transform.SetWorldPosition({ -3.0f, -1.0f, -1.0f }); - transform.SetLocalScale({ 5.0f, 5.0f, 5.0f }); - - //auto entity = SHEntityManager::CreateEntity(); - //auto& renderable = *SHComponentManager::GetComponent_s(entity); - //auto& transform = *SHComponentManager::GetComponent_s(entity); - - //renderable.Mesh = handles.back(); + //renderable.Mesh = handles.front(); //renderable.SetMaterial(customMat); + //renderable.GetModifiableMaterial()->SetProperty("data.color", SHVec4(0.0f, 0.0f, 0.0f, 0.0f)); + //renderable.GetModifiableMaterial()->SetProperty("data.alpha", 1.0f); + //renderable.GetModifiableMaterial()->SetProperty("data.textureIndex", 1); - //transform.SetLocalScale(TEST_OBJ_SCALE); - //transform.SetWorldPosition({-1.0f, -1.0f, -1.0f}); + //transform.SetWorldPosition({ -3.0f, -1.0f, -1.0f }); + //transform.SetLocalScale({ 5.0f, 5.0f, 5.0f }); + + auto entity = SHEntityManager::CreateEntity(); + auto& renderable = *SHComponentManager::GetComponent_s(entity); + auto& transform = *SHComponentManager::GetComponent_s(entity); + auto& rb = *SHComponentManager::GetComponent_s(entity); + + renderable.Mesh = CUBE_MESH; + renderable.SetMaterial(customMat); + + transform.SetLocalScale(SHVec3::One * 0.25f); + transform.SetWorldPosition({0.0f, 2.0f, -1.0f}); // Create blank entity with a script //testObj = SHADE::SHEntityManager::CreateEntity(); - //auto& testObjRenderable = *SHComponentManager::GetComponent_s(testObj); + //auto& testObjRenderable = *SHComponentManager::GetComponent(testObj); //testObjRenderable.Mesh = CUBE_MESH; //testObjRenderable.SetMaterial(matInst); - SHADE::SHScriptEngine* scriptEngine = static_cast(SHADE::SHSystemManager::GetSystem()); - scriptEngine->AddScript(raccoonSpin, "RaccoonSpin"); - auto raccoonShowcase = SHEntityManager::CreateEntity(); - auto& renderableShowcase = *SHComponentManager::GetComponent_s(raccoonShowcase); - auto& transformShowcase = *SHComponentManager::GetComponent_s(raccoonShowcase); + //SHADE::SHScriptEngine* scriptEngine = static_cast(SHADE::SHSystemManager::GetSystem()); + //scriptEngine->AddScript(raccoonSpin, "RaccoonSpin"); - renderableShowcase.Mesh = handles.front(); - renderableShowcase.SetMaterial(customMat); - renderableShowcase.GetModifiableMaterial()->SetProperty("data.color", SHVec4(0.0f, 0.0f, 0.0f, 0.0f)); - renderableShowcase.GetModifiableMaterial()->SetProperty("data.alpha", 1.0f); - renderableShowcase.GetModifiableMaterial()->SetProperty("data.textureIndex", 1); + //auto raccoonShowcase = SHEntityManager::CreateEntity(); + //auto& renderableShowcase = *SHComponentManager::GetComponent_s(raccoonShowcase); + //auto& transformShowcase = *SHComponentManager::GetComponent_s(raccoonShowcase); - transformShowcase.SetWorldPosition({ 3.0f, -1.0f, -1.0f }); - transformShowcase.SetLocalScale({ 5.0f, 5.0f, 5.0f }); - scriptEngine->AddScript(raccoonShowcase, "RaccoonShowcase"); + //renderableShowcase.Mesh = handles.front(); + //renderableShowcase.SetMaterial(customMat); + //renderableShowcase.GetModifiableMaterial()->SetProperty("data.color", SHVec4(0.0f, 0.0f, 0.0f, 0.0f)); + //renderableShowcase.GetModifiableMaterial()->SetProperty("data.alpha", 1.0f); + //renderableShowcase.GetModifiableMaterial()->SetProperty("data.textureIndex", 1); + + //transformShowcase.SetWorldPosition({ 3.0f, -1.0f, -1.0f }); + //transformShowcase.SetLocalScale({ 5.0f, 5.0f, 5.0f }); + //scriptEngine->AddScript(raccoonShowcase, "RaccoonShowcase"); } void SBTestScene::Update(float dt) diff --git a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp index 04cb00dd..e2cd1e4b 100644 --- a/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp +++ b/SHADE_Engine/src/Physics/Components/SHRigidBodyComponent.cpp @@ -37,6 +37,9 @@ namespace SHADE // Set default flags: Gravity & Sleeping enabled flags |= 1U << 0; flags |= 1U << 1; + + // Set all dirty flags to true + dirtyFlags = 1023; } /*-----------------------------------------------------------------------------------*/ diff --git a/SHADE_Engine/src/Physics/SHPhysicsObject.cpp b/SHADE_Engine/src/Physics/SHPhysicsObject.cpp index 325d860f..f489624d 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsObject.cpp +++ b/SHADE_Engine/src/Physics/SHPhysicsObject.cpp @@ -79,14 +79,40 @@ namespace SHADE } /*-----------------------------------------------------------------------------------*/ - /* Public Function Member Definitions */ + /* Setter Function Definitions */ /*-----------------------------------------------------------------------------------*/ + void SHPhysicsObject::SetPosition(const SHVec3& position) const noexcept + { + const rp3d::Vector3 RP3D_POS { position.x, position.y, position.z }; - /*-----------------------------------------------------------------------------------*/ - /* Private Function Member Definitions */ - /*-----------------------------------------------------------------------------------*/ + rp3d::Transform rp3dTF; + rp3dTF.setPosition(RP3D_POS); + rp3dTF.setOrientation(rp3dBody->getTransform().getOrientation()); + + rp3dBody->setTransform(rp3dTF); + } + + void SHPhysicsObject::SetOrientation(const SHQuaternion& orientation) const noexcept + { + const rp3d::Quaternion RP3D_ORIENTATION { orientation.x, orientation.y, orientation.z, orientation.w }; + + rp3d::Transform rp3dTF; + rp3dTF.setPosition(rp3dBody->getTransform().getPosition()); + rp3dTF.setOrientation(RP3D_ORIENTATION); + + rp3dBody->setTransform(rp3dTF); + } + + void SHPhysicsObject::SetRotation(const SHVec3& rotation) const noexcept + { + const rp3d::Quaternion RP3D_ORIENTATION = rp3d::Quaternion::fromEulerAngles( rotation.x, rotation.y, rotation.z ); + + rp3d::Transform rp3dTF; + rp3dTF.setPosition(rp3dBody->getTransform().getPosition()); + rp3dTF.setOrientation(RP3D_ORIENTATION); + + rp3dBody->setTransform(rp3dTF); + } - - } // namespace SHADE \ No newline at end of file diff --git a/SHADE_Engine/src/Physics/SHPhysicsObject.h b/SHADE_Engine/src/Physics/SHPhysicsObject.h index e0f0f38f..cd9be57b 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsObject.h +++ b/SHADE_Engine/src/Physics/SHPhysicsObject.h @@ -55,14 +55,18 @@ namespace SHADE /* Getter Functions */ /*---------------------------------------------------------------------------------*/ - [[nodiscard]] virtual SHVec3 GetPosition () const noexcept; - [[nodiscard]] virtual SHQuaternion GetOrientation () const noexcept; - [[nodiscard]] virtual SHVec3 GetRotation () const noexcept; + [[nodiscard]] SHVec3 GetPosition () const noexcept; + [[nodiscard]] SHQuaternion GetOrientation () const noexcept; + [[nodiscard]] SHVec3 GetRotation () const noexcept; /*---------------------------------------------------------------------------------*/ - /* Function Members */ + /* Setter Functions */ /*---------------------------------------------------------------------------------*/ + void SetPosition (const SHVec3& position) const noexcept; + void SetOrientation (const SHQuaternion& orientation) const noexcept; + void SetRotation (const SHVec3& rotation) const noexcept; + private: /*---------------------------------------------------------------------------------*/ /* Data Members */ diff --git a/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp b/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp index 9be8a5ef..59d915f9 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp +++ b/SHADE_Engine/src/Physics/SHPhysicsSystem.cpp @@ -27,7 +27,7 @@ namespace SHADE SHPhysicsSystem::SHPhysicsSystem() : interpolationFactor { 0.0 } - , fixedDT { 1.0 / 60.0 } + , fixedDT { 60.0 } , world { nullptr } {} @@ -204,7 +204,11 @@ namespace SHADE // Check if entity is already a physics object auto* physicsObject = GetPhysicsObject(entityID); if (!physicsObject) + { physicsObject = &(map.emplace(entityID, SHPhysicsObject{}).first->second); + physicsObject->entityID = entityID; + } + // Get entity transform auto const* SHADE_TF = SHComponentManager::GetComponent_s(entityID); @@ -292,9 +296,23 @@ namespace SHADE { auto* system = reinterpret_cast(GetSystem()); + // Get dense arrays + auto& rbDense = SHComponentManager::GetDense(); + auto& cDense = SHComponentManager::GetDense(); + // Update bodies and colliders if component is dirty - const auto& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); - system->SyncComponents(sceneGraph); + system->SyncRigidBodyComponents(rbDense); + + // Sync transforms + for (auto& physicsObject : system->map | std::views::values) + { + const auto* TF = SHComponentManager::GetComponent(physicsObject.entityID); + if (TF->HasChanged()) + { + physicsObject.SetPosition(TF->GetWorldPosition()); + physicsObject.SetRotation(TF->GetWorldRotation()); + } + } } void SHPhysicsSystem::PhysicsFixedUpdate::Execute(double dt) noexcept @@ -322,8 +340,7 @@ namespace SHADE auto* system = reinterpret_cast(GetSystem()); // Interpolate transforms for rendering - const auto& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); - system->SyncTransforms(sceneGraph); + system->SyncTransforms(); // TODO(Diren): Handle trigger messages for scripting } @@ -344,89 +361,67 @@ namespace SHADE return &(it->second); } - void SHPhysicsSystem::SyncComponents(const SHSceneGraph& sceneGraph) noexcept + void SHPhysicsSystem::SyncRigidBodyComponents(std::vector& denseArray) noexcept { - static const auto SYNC_COMPONENTS = [&](SHSceneNode* node) + if (denseArray.empty()) + return; + + for (auto& comp : denseArray) { - const EntityID ENTITY_ID = node->GetEntityID(); + const EntityID ENTITY_ID = comp.GetEID(); - // Get physics object + // Get physicsObject auto const* physicsObject = GetPhysicsObject(ENTITY_ID); - if (!physicsObject) - return; - const bool RP3D_ACTIVE = physicsObject->rp3dBody->isActive(); - const bool NODE_ACTIVE = node->IsActive(); + const bool RP3D_ACTIVE = physicsObject->rp3dBody->isActive(); + // TODO(Diren): Check if active in hierarchy + const bool COMPONENT_ACTIVE = comp.isActive; - // Sync rigid body - if (physicsObject->isRigidBody) + if (RP3D_ACTIVE != COMPONENT_ACTIVE) + physicsObject->rp3dBody->setIsActive(COMPONENT_ACTIVE); + + if (!COMPONENT_ACTIVE) + continue; + + if (comp.dirtyFlags > 0) { - auto* rbComponent = SHComponentManager::GetComponent_s(ENTITY_ID); - if (rbComponent->dirtyFlags > 0) - { - SyncRB(physicsObject, rbComponent); - rbComponent->dirtyFlags = 0; - } - - - // Sync active states - const bool SHADE_ACTIVE = NODE_ACTIVE && rbComponent->isActive; - if (SHADE_ACTIVE != RP3D_ACTIVE) - physicsObject->rp3dBody->setIsActive(SHADE_ACTIVE); + SyncRB(physicsObject, &comp); + comp.dirtyFlags = 0; } - - // Sync colliders - if (physicsObject->hasColliders) - { - auto const* colliderComponent = SHComponentManager::GetComponent_s(ENTITY_ID); - - } - - // Sync transforms - auto const* tfComponent = SHComponentManager::GetComponent(ENTITY_ID); - if (tfComponent->HasChanged()) - { - const SHVec3& SHADE_POS = tfComponent->GetWorldPosition(); - const SHVec3& SHADE_ROT = tfComponent->GetWorldRotation(); - - const rp3d::Vector3 RP3D_POS { SHADE_POS.x, SHADE_POS.y, SHADE_POS.z }; - const rp3d::Quaternion RP3D_ROT = rp3d::Quaternion::fromEulerAngles(SHADE_ROT.x, SHADE_ROT.y, SHADE_ROT.z); - - physicsObject->rp3dBody->setTransform(rp3d::Transform{ RP3D_POS, RP3D_ROT }); - } - }; - - sceneGraph.Traverse(SYNC_COMPONENTS); + } } - void SHPhysicsSystem::SyncTransforms(const SHSceneGraph& sceneGraph) noexcept + void SHPhysicsSystem::SyncTransforms() noexcept { - static const auto SYNC_TRANSFORMS = [&](SHSceneNode* node) + for (auto& pair : map) { - const EntityID ENTITY_ID = node->GetEntityID(); - - // Get physics object - auto* physicsObject = GetPhysicsObject(ENTITY_ID); - if (!physicsObject) - return; - - auto* tfComponent = SHComponentManager::GetComponent_s(ENTITY_ID); + const EntityID ENTITY_ID = pair.first; + SHPhysicsObject& physicsObject = pair.second; rp3d::Vector3 rp3dPos; rp3d::Quaternion rp3dRot; - const rp3d::Transform CURRENT_TF = physicsObject->rp3dBody->getTransform(); + const rp3d::Transform CURRENT_TF = physicsObject.rp3dBody->getTransform(); // Check if transform should be interpolated - auto const* rbComponent = SHComponentManager::GetComponent_s(ENTITY_ID); - if (rbComponent && rbComponent->IsInterpolating()) + + if (physicsObject.isRigidBody) { - const rp3d::Transform PREV_TF = physicsObject->prevTransform; - const rp3d::Transform INTERPOLATED_TF = rp3d::Transform::interpolateTransforms(PREV_TF, CURRENT_TF, static_cast(interpolationFactor)); + auto const* rbComponent = SHComponentManager::GetComponent(ENTITY_ID); + if (rbComponent->IsInterpolating()) + { + const rp3d::Transform PREV_TF = physicsObject.prevTransform; + const rp3d::Transform INTERPOLATED_TF = rp3d::Transform::interpolateTransforms(PREV_TF, CURRENT_TF, static_cast(interpolationFactor)); - rp3dPos = INTERPOLATED_TF.getPosition(); - rp3dRot = INTERPOLATED_TF.getOrientation(); + rp3dPos = INTERPOLATED_TF.getPosition(); + rp3dRot = INTERPOLATED_TF.getOrientation(); + } + else + { + rp3dPos = CURRENT_TF.getPosition(); + rp3dRot = CURRENT_TF.getOrientation(); + } } else { @@ -438,14 +433,13 @@ namespace SHADE const SHVec3 SHADE_POS = SHVec3{ rp3dPos.x, rp3dPos.y, rp3dPos.z }; const SHVec3 SHADE_ROT = SHQuaternion{ rp3dRot.x, rp3dRot.y, rp3dRot.z, rp3dRot.w }.ToEuler(); + auto* tfComponent = SHComponentManager::GetComponent(ENTITY_ID); tfComponent->SetWorldPosition(SHADE_POS); tfComponent->SetWorldRotation(SHADE_ROT); // Cache transforms - physicsObject->prevTransform = CURRENT_TF; - }; - - sceneGraph.Traverse(SYNC_TRANSFORMS); + physicsObject.prevTransform = CURRENT_TF; + } } void SHPhysicsSystem::SyncRB(SHPhysicsObject const* physicsObject, const SHRigidBodyComponent* comp) noexcept @@ -527,9 +521,9 @@ namespace SHADE { const rp3d::Vector3 CONSTRAINTS { - rbFlags & 1U << 2 ? 1.0f : 0.0f, - rbFlags & 1U << 3 ? 1.0f : 0.0f, - rbFlags & 1U << 4 ? 1.0f : 0.0f + rbFlags & 1U << 2 ? 0.0f : 1.0f, + rbFlags & 1U << 3 ? 0.0f : 1.0f, + rbFlags & 1U << 4 ? 0.0f : 1.0f }; @@ -540,9 +534,9 @@ namespace SHADE { const rp3d::Vector3 CONSTRAINTS { - rbFlags & 1U << 5 ? 1.0f : 0.0f, - rbFlags & 1U << 6 ? 1.0f : 0.0f, - rbFlags & 1U << 7 ? 1.0f : 0.0f + rbFlags & 1U << 5 ? 0.0f : 1.0f, + rbFlags & 1U << 6 ? 0.0f : 1.0f, + rbFlags & 1U << 7 ? 0.0f : 1.0f }; rp3dRigidBody->setAngularLockAxisFactor(CONSTRAINTS); diff --git a/SHADE_Engine/src/Physics/SHPhysicsSystem.h b/SHADE_Engine/src/Physics/SHPhysicsSystem.h index af615f35..dbf0a597 100644 --- a/SHADE_Engine/src/Physics/SHPhysicsSystem.h +++ b/SHADE_Engine/src/Physics/SHPhysicsSystem.h @@ -183,8 +183,9 @@ namespace SHADE /*---------------------------------------------------------------------------------*/ SHPhysicsObject* GetPhysicsObject (EntityID entityID) noexcept; - void SyncComponents (const SHSceneGraph& sceneGraph) noexcept; - void SyncTransforms (const SHSceneGraph& sceneGraph) noexcept; + void SyncRigidBodyComponents (std::vector& denseArray) noexcept; + void SyncColliderComponents (std::vector& denseArray) noexcept; + void SyncTransforms () noexcept; // TODO(Diren): Trigger handling static void SyncRB (SHPhysicsObject const* physicsObject, const SHRigidBodyComponent* comp) noexcept; From aef3e4ef1affbcf63f365d426f17bfcfc185850b Mon Sep 17 00:00:00 2001 From: mushgunAX Date: Sat, 1 Oct 2022 17:04:07 +0800 Subject: [PATCH 10/17] Update SBApplication.cpp --- SHADE_Application/src/Application/SBApplication.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/SHADE_Application/src/Application/SBApplication.cpp b/SHADE_Application/src/Application/SBApplication.cpp index 8fbf1858..606ab4e2 100644 --- a/SHADE_Application/src/Application/SBApplication.cpp +++ b/SHADE_Application/src/Application/SBApplication.cpp @@ -58,7 +58,6 @@ namespace Sandbox // TODO(Diren): Create Physics System here SHADE::SHSystemManager::CreateSystem(); SHADE::SHGraphicsSystem* graphicsSystem = static_cast(SHADE::SHSystemManager::GetSystem()); - SHADE::SHSystemManager::CreateSystem(); SHADE::SHSystemManager::CreateSystem(); // Create Routines From 3c58a538ae12afef869eb4129513f56a486db580 Mon Sep 17 00:00:00 2001 From: mushgunAX Date: Sat, 1 Oct 2022 18:02:27 +0800 Subject: [PATCH 11/17] Mouse Vel & UpdateInput called from SBApplication --- SHADE_Application/src/Application/SBApplication.cpp | 1 + SHADE_Engine/src/Input/SHInputManager.cpp | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/SHADE_Application/src/Application/SBApplication.cpp b/SHADE_Application/src/Application/SBApplication.cpp index 606ab4e2..fc3e02ad 100644 --- a/SHADE_Application/src/Application/SBApplication.cpp +++ b/SHADE_Application/src/Application/SBApplication.cpp @@ -118,6 +118,7 @@ namespace Sandbox while (!window.WindowShouldClose()) { SHFrameRateController::UpdateFRC(); + SHInputManager::UpdateInput(SHFrameRateController::GetRawDeltaTime()); SHSceneManager::UpdateSceneManager(); SHSceneManager::SceneUpdate(1/60.0f); //#ifdef SHEDITOR diff --git a/SHADE_Engine/src/Input/SHInputManager.cpp b/SHADE_Engine/src/Input/SHInputManager.cpp index 619afec0..04f2b02e 100644 --- a/SHADE_Engine/src/Input/SHInputManager.cpp +++ b/SHADE_Engine/src/Input/SHInputManager.cpp @@ -112,6 +112,10 @@ namespace SHADE mouseScreenX = p.x; mouseScreenY = p.y; + //Velocity + mouseVelocityX = static_cast(mouseScreenX - mouseScreenXLast) / dt; + mouseVelocityY = static_cast(mouseScreenY - mouseScreenYLast) / dt; + //Mouse wheel vertical delta updating mouseWheelVerticalDelta = 0; mouseWheelVerticalDelta = mouseWheelVerticalDeltaPoll; From a6e17847bf54968818084a5e935b1d01008890cf Mon Sep 17 00:00:00 2001 From: Sri Sham Haran Date: Sat, 1 Oct 2022 18:58:13 +0800 Subject: [PATCH 12/17] Warning disables Remove SDL hint that gave warning (it was unnecessary anyway) --- SHADE_Application/premake5.lua | 9 ++++++++- SHADE_Application/src/Application/SBApplication.cpp | 1 - SHADE_Engine/premake5.lua | 9 ++++++++- SHADE_Managed/premake5.lua | 6 ++++++ 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/SHADE_Application/premake5.lua b/SHADE_Application/premake5.lua index 2119808d..a02b7f2a 100644 --- a/SHADE_Application/premake5.lua +++ b/SHADE_Application/premake5.lua @@ -67,9 +67,16 @@ project "SHADE_Application" disablewarnings { - "4251" + "4251", + "26812", + "26439", + "26451", + "26437", + "4275" } + linkoptions { "-IGNORE:4006" } + warnings 'Extra' filter "configurations:Debug" diff --git a/SHADE_Application/src/Application/SBApplication.cpp b/SHADE_Application/src/Application/SBApplication.cpp index b982557c..5e57e6a5 100644 --- a/SHADE_Application/src/Application/SBApplication.cpp +++ b/SHADE_Application/src/Application/SBApplication.cpp @@ -14,7 +14,6 @@ #include #include #include -#define SDL_HINT_VIDEO_FOREIGN_WINDOW_VULKAN 1 #include #include "Scripting/SHScriptEngine.h" diff --git a/SHADE_Engine/premake5.lua b/SHADE_Engine/premake5.lua index f11ccf79..5481fa7d 100644 --- a/SHADE_Engine/premake5.lua +++ b/SHADE_Engine/premake5.lua @@ -76,8 +76,15 @@ project "SHADE_Engine" disablewarnings { - "4251" + "4251", + "26812", + "26439", + "26451", + "26437", + "4275" } + + linkoptions { "-IGNORE:4006" } defines { diff --git a/SHADE_Managed/premake5.lua b/SHADE_Managed/premake5.lua index a7b20144..9724c296 100644 --- a/SHADE_Managed/premake5.lua +++ b/SHADE_Managed/premake5.lua @@ -61,6 +61,12 @@ project "SHADE_Managed" "MultiProcessorCompile" } + disablewarnings + { + "4275" + } + + dependson { "yaml-cpp", From c5efefcf4f3f4140f4226eebbdd01f6b9f830c7e Mon Sep 17 00:00:00 2001 From: Sri Sham Haran Date: Sat, 1 Oct 2022 21:18:54 +0800 Subject: [PATCH 13/17] Editor warning fixes --- .../src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp | 2 +- SHADE_Engine/src/Editor/IconsMaterialDesign.h | 2 +- SHADE_Engine/src/Editor/SHEditorWidgets.hpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp index f787d4db..25cd5a6a 100644 --- a/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp +++ b/SHADE_Engine/src/Editor/EditorWindow/HierarchyPanel/SHHierarchyPanel.cpp @@ -114,7 +114,7 @@ namespace SHADE auto* entity = SHEntityManager::GetEntityByID(currentNode->GetEntityID()); //Draw Node - bool isNodeOpen = ImGui::TreeNodeEx((void*)eid, nodeFlags, "%u: %s", EntityHandleGenerator::GetIndex(eid), entity->name.c_str()); + bool isNodeOpen = ImGui::TreeNodeEx(reinterpret_cast(entity), nodeFlags, "%u: %s", EntityHandleGenerator::GetIndex(eid), entity->name.c_str()); const ImRect nodeRect = ImRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()); //Check For Begin Drag diff --git a/SHADE_Engine/src/Editor/IconsMaterialDesign.h b/SHADE_Engine/src/Editor/IconsMaterialDesign.h index 68373237..3f15892b 100644 --- a/SHADE_Engine/src/Editor/IconsMaterialDesign.h +++ b/SHADE_Engine/src/Editor/IconsMaterialDesign.h @@ -843,7 +843,7 @@ #define ICON_MD_FLIP_TO_FRONT "\xee\xa2\x83" // U+e883 #define ICON_MD_FLOOD "\xee\xaf\xa6" // U+ebe6 #define ICON_MD_FLOURESCENT "\xee\xb0\xb1" // U+ec31 -#define ICON_MD_FLOURESCENT "\xef\x80\x8d" // U+f00d +#define ICON_MD_FLOURESCENT2 "\xef\x80\x8d" // U+f00d #define ICON_MD_FLUORESCENT "\xee\xb0\xb1" // U+ec31 #define ICON_MD_FLUTTER_DASH "\xee\x80\x8b" // U+e00b #define ICON_MD_FMD_BAD "\xef\x80\x8e" // U+f00e diff --git a/SHADE_Engine/src/Editor/SHEditorWidgets.hpp b/SHADE_Engine/src/Editor/SHEditorWidgets.hpp index 88cea814..8d2adcc6 100644 --- a/SHADE_Engine/src/Editor/SHEditorWidgets.hpp +++ b/SHADE_Engine/src/Editor/SHEditorWidgets.hpp @@ -327,7 +327,7 @@ namespace SHADE ImGui::PushID(fieldLabel.c_str()); ImGui::Text(fieldLabel.c_str()); ImGui::SameLine(); - if (edited = ImGui::Combo("##Combo", &selected, list.data(), list.size())) + if (edited = ImGui::Combo("##Combo", &selected, list.data(), static_cast(list.size()))) { SHCommandManager::PerformCommand(std::reinterpret_pointer_cast(std::make_shared>(get(), selected, set)), false); } From 8a3a08986bd0faa54c01431850c9d5e2404b1eb3 Mon Sep 17 00:00:00 2001 From: Glence Date: Sat, 1 Oct 2022 21:29:40 +0800 Subject: [PATCH 14/17] fix audiosystem warnings --- SHADE_Engine/src/AudioSystem/SHAudioSystem.cpp | 4 ++-- SHADE_Engine/src/AudioSystem/SHAudioSystem.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/SHADE_Engine/src/AudioSystem/SHAudioSystem.cpp b/SHADE_Engine/src/AudioSystem/SHAudioSystem.cpp index 2482fe8e..c3c7ef03 100644 --- a/SHADE_Engine/src/AudioSystem/SHAudioSystem.cpp +++ b/SHADE_Engine/src/AudioSystem/SHAudioSystem.cpp @@ -90,7 +90,7 @@ namespace SHADE //PlayEventOnce("event:/SFX/Dawn/Dawn_Attack"); } - void SHADE::SHAudioSystem::Run(float dt) + void SHADE::SHAudioSystem::Run(double dt) { static_cast(dt); //if (GetKeyState(VK_SPACE) & 0x8000) @@ -417,7 +417,7 @@ namespace SHADE int instanceCount = 0; event.second->getInstanceCount(&instanceCount); std::vector instances(instanceCount); - event.second->getInstanceList(instances.data(), instances.size(), &instanceCount); + event.second->getInstanceList(instances.data(), static_cast(instances.size()), &instanceCount); for (auto const& instance : instances) { instance->setPaused(pause); diff --git a/SHADE_Engine/src/AudioSystem/SHAudioSystem.h b/SHADE_Engine/src/AudioSystem/SHAudioSystem.h index 04fad1f0..f19fcc3b 100644 --- a/SHADE_Engine/src/AudioSystem/SHAudioSystem.h +++ b/SHADE_Engine/src/AudioSystem/SHAudioSystem.h @@ -50,7 +50,7 @@ namespace SHADE ~SHAudioSystem(); void Init(); - void Run(float dt); + void Run(double dt); class SH_API AudioRoutine final : public SHSystemRoutine { public: From 8e60d4b771d19a2c09e867d6a7bf909d3ad495ad Mon Sep 17 00:00:00 2001 From: Xiao Qi Date: Sat, 1 Oct 2022 23:42:54 +0800 Subject: [PATCH 15/17] Changed asserts to SHLOG related functions --- SHADE_Engine/src/Filesystem/SHFileSystem.cpp | 33 ++++++++++++++------ 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/SHADE_Engine/src/Filesystem/SHFileSystem.cpp b/SHADE_Engine/src/Filesystem/SHFileSystem.cpp index 16175578..bd34ed71 100644 --- a/SHADE_Engine/src/Filesystem/SHFileSystem.cpp +++ b/SHADE_Engine/src/Filesystem/SHFileSystem.cpp @@ -2,7 +2,6 @@ #include "SHFileSystem.h" #include "fileapi.h" #include -#include #include namespace SHADE @@ -27,8 +26,11 @@ namespace SHADE } auto const count = static_cast(folders[here]->subFolders.size()); - - assert(count < FOLDER_MAX_COUNT, "Max subfolders reached\n"); + + if (count >= FOLDER_MAX_COUNT) + { + SHLOG_ERROR("Max subfolder reached: {}\n", name); + } auto const location = static_cast(count); @@ -37,7 +39,10 @@ namespace SHADE return location; } - assert(folders.contains(here), "Folder creation location does not exist/invalid\n"); + if (!folders.contains(here)) + { + SHLOG_ERROR("Folder creation location does not exist/invalid: {}\n", here); + } auto const count = static_cast(folders[here]->subFolders.size()); @@ -45,7 +50,11 @@ namespace SHADE location <<= FOLDER_BIT_ALLOCATE; location |= count; - assert(count < FOLDER_MAX_COUNT, "Max subfolders reached\n"); + if (count >= FOLDER_MAX_COUNT) + { + SHLOG_ERROR("Max subfolder reached: {}\n", name); + } + CreateFolder(folders[0]->path, here, location, name); return location; @@ -53,7 +62,10 @@ namespace SHADE bool SHFileSystem::DeleteFolder(FolderPointer location) noexcept { - assert(folders.contains(location->id), "Delete target does not exist/invalid.\n"); + if (!folders.contains(location->id)) + { + SHLOG_ERROR("Delete target does not exist/invalid: {}\n", location->name); + } for (auto const& subFolder : folders[location->id]->subFolders) { @@ -116,10 +128,11 @@ namespace SHADE FolderPointer SHFileSystem::CreateFolder(FolderPath path, FolderLocation parent, FolderHandle location, FolderName name) noexcept { - assert( - CreateDirectoryA(path.c_str(), nullptr), - "Failed to create folder\n" - ); + + if (!CreateDirectoryA(path.c_str(), nullptr)) + { + SHLOG_ERROR("Failed to create folder: {}\n", path); + } folders[location] = std::make_unique(location, name); folders[location]->path = path; From 61e353164bc3fe9aed6f1df550d2c5743054104e Mon Sep 17 00:00:00 2001 From: Xiao Qi Date: Sat, 1 Oct 2022 23:57:26 +0800 Subject: [PATCH 16/17] Fixed all asset related warnings --- .../src/Assets/Asset Types/SHTextureAsset.h | 6 +++-- .../src/Assets/Libraries/SHMeshLoader.cpp | 4 +-- .../src/Assets/Libraries/SHTextureLoader.cpp | 8 +++--- SHADE_Engine/src/Assets/SHAssetManager.cpp | 26 ++++++++++--------- .../src/Assets/SHAssetMetaHandler.cpp | 2 +- .../MiddleEnd/Textures/SHTextureLibrary.h | 2 +- 6 files changed, 26 insertions(+), 22 deletions(-) diff --git a/SHADE_Engine/src/Assets/Asset Types/SHTextureAsset.h b/SHADE_Engine/src/Assets/Asset Types/SHTextureAsset.h index 634d9a9a..07cebea9 100644 --- a/SHADE_Engine/src/Assets/Asset Types/SHTextureAsset.h +++ b/SHADE_Engine/src/Assets/Asset Types/SHTextureAsset.h @@ -17,7 +17,8 @@ namespace SHADE SHTexture::PixelChannel const * pixelData; SHTextureAsset() - : numBytes{ 0 }, + : compiled{ false }, + numBytes{ 0 }, width{ 0 }, height{ 0 }, format{ SHTexture::TextureFormat::eUndefined }, @@ -25,7 +26,8 @@ namespace SHADE {} SHTextureAsset(SHTextureAsset const& rhs) - : numBytes{ rhs.numBytes }, + : compiled{ false }, + numBytes{ rhs.numBytes }, width{ rhs.width }, height{ rhs.height }, format{ rhs.format }, diff --git a/SHADE_Engine/src/Assets/Libraries/SHMeshLoader.cpp b/SHADE_Engine/src/Assets/Libraries/SHMeshLoader.cpp index b77d429d..3a5fb9ec 100644 --- a/SHADE_Engine/src/Assets/Libraries/SHMeshLoader.cpp +++ b/SHADE_Engine/src/Assets/Libraries/SHMeshLoader.cpp @@ -91,8 +91,8 @@ namespace SHADE } } - result.header.vertexCount = result.vertexPosition.size(); - result.header.indexCount = result.indices.size(); + result.header.vertexCount = static_cast(result.vertexPosition.size()); + result.header.indexCount = static_cast(result.indices.size()); result.header.meshName = mesh.mName.C_Str(); return result; diff --git a/SHADE_Engine/src/Assets/Libraries/SHTextureLoader.cpp b/SHADE_Engine/src/Assets/Libraries/SHTextureLoader.cpp index 1047cdc6..47501d42 100644 --- a/SHADE_Engine/src/Assets/Libraries/SHTextureLoader.cpp +++ b/SHADE_Engine/src/Assets/Libraries/SHTextureLoader.cpp @@ -83,10 +83,10 @@ namespace SHADE std::vector mipOff(file.GetMipCount()); - for (auto i{0}; i < file.GetMipCount(); ++i) + for (size_t i{0}; i < file.GetMipCount(); ++i) { - mipOff[i] = totalBytes; - totalBytes += file.GetImageData(i, 0)->m_memSlicePitch; + mipOff[i] = static_cast(totalBytes); + totalBytes += file.GetImageData(static_cast(i), 0)->m_memSlicePitch; } SHTexture::PixelChannel* pixel = new SHTexture::PixelChannel[totalBytes]; @@ -94,7 +94,7 @@ namespace SHADE //pixel = std::move(reinterpret_cast(file.GetDDSData())); asset.compiled = false; - asset.numBytes = totalBytes; + asset.numBytes = static_cast(totalBytes); asset.width = file.GetWidth(); asset.height = file.GetHeight(); asset.format = ddsLoaderToVkFormat(file.GetFormat(), true); diff --git a/SHADE_Engine/src/Assets/SHAssetManager.cpp b/SHADE_Engine/src/Assets/SHAssetManager.cpp index 989cd2ad..430b8c79 100644 --- a/SHADE_Engine/src/Assets/SHAssetManager.cpp +++ b/SHADE_Engine/src/Assets/SHAssetManager.cpp @@ -72,12 +72,13 @@ namespace SHADE AssetType type = SHAssetMetaHandler::GetTypeFromExtension(path.extension().string().c_str()); std::string folder; - switch (type) - { - default: - //TODO:ASSERT UNSUPPORTED FILE TYPE - return std::filesystem::path(); - } + //TODO Implement asset type generation + //switch (type) + //{ + //default: + // //TODO:ASSERT UNSUPPORTED FILE TYPE + // return std::filesystem::path(); + //} return std::filesystem::path(ASSET_ROOT + folder + path.filename().string()); } @@ -108,12 +109,13 @@ namespace SHADE meta.type = type; std::string folder; - switch (type) - { - default: - folder = ""; - break; - } + //TODO implement folder choosing + //switch (type) + //{ + //default: + // folder = ""; + // break; + //} AssetPath path{ ASSET_ROOT + folder + name + SHAssetMetaHandler::GetExtensionFromType(type) }; SHAssetMetaHandler::WriteMetaData(meta); diff --git a/SHADE_Engine/src/Assets/SHAssetMetaHandler.cpp b/SHADE_Engine/src/Assets/SHAssetMetaHandler.cpp index 35d167d2..6554a3e4 100644 --- a/SHADE_Engine/src/Assets/SHAssetMetaHandler.cpp +++ b/SHADE_Engine/src/Assets/SHAssetMetaHandler.cpp @@ -122,7 +122,7 @@ namespace SHADE break; default: - void; + break; } metaFile.close(); diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Textures/SHTextureLibrary.h b/SHADE_Engine/src/Graphics/MiddleEnd/Textures/SHTextureLibrary.h index 660d93eb..c2eb85ec 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Textures/SHTextureLibrary.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Textures/SHTextureLibrary.h @@ -37,7 +37,7 @@ namespace SHADE class SHVkDescriptorSetLayout; class SHVkDescriptorSetGroup; class SHVkSampler; - class SHTextureAsset; + struct SHTextureAsset; /*---------------------------------------------------------------------------------*/ /* Type Definitions */ From 40bcea133d1089c2e060afdeda20d1b977901b0e Mon Sep 17 00:00:00 2001 From: Xiao Qi Date: Sun, 2 Oct 2022 00:09:38 +0800 Subject: [PATCH 17/17] Changed texture index to 0 for both racoons --- SHADE_Application/src/Scenes/SBTestScene.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SHADE_Application/src/Scenes/SBTestScene.cpp b/SHADE_Application/src/Scenes/SBTestScene.cpp index ffecdf95..3b277e6c 100644 --- a/SHADE_Application/src/Scenes/SBTestScene.cpp +++ b/SHADE_Application/src/Scenes/SBTestScene.cpp @@ -118,7 +118,7 @@ namespace Sandbox renderable.SetMaterial(customMat); renderable.GetModifiableMaterial()->SetProperty("data.color", SHVec4(0.0f, 0.0f, 0.0f, 0.0f)); renderable.GetModifiableMaterial()->SetProperty("data.alpha", 1.0f); - renderable.GetModifiableMaterial()->SetProperty("data.textureIndex", 1); + renderable.GetModifiableMaterial()->SetProperty("data.textureIndex", 0); transform.SetWorldPosition({ -3.0f, -1.0f, -1.0f }); transform.SetLocalScale({ 5.0f, 5.0f, 5.0f }); @@ -159,7 +159,7 @@ namespace Sandbox renderableShowcase.SetMaterial(customMat); renderableShowcase.GetModifiableMaterial()->SetProperty("data.color", SHVec4(0.0f, 0.0f, 0.0f, 0.0f)); renderableShowcase.GetModifiableMaterial()->SetProperty("data.alpha", 1.0f); - renderableShowcase.GetModifiableMaterial()->SetProperty("data.textureIndex", 1); + renderableShowcase.GetModifiableMaterial()->SetProperty("data.textureIndex", 0); transformShowcase.SetWorldPosition({ 3.0f, -1.0f, -1.0f }); transformShowcase.SetLocalScale({ 5.0f, 5.0f, 5.0f });