From 54ded62757e3ecb6755d2357f543659017d7cd80 Mon Sep 17 00:00:00 2001 From: Daniel Seiler Date: Sat, 27 Jan 2024 21:37:30 +0100 Subject: [PATCH 01/50] Update README.md (#1438) Add warning about docker-compose on windows --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 1d998511..f0f2ac36 100644 --- a/README.md +++ b/README.md @@ -356,6 +356,10 @@ The Darkflame Server is automatically built and published as a Docker Container ## Compose +> [!WARNING] +> It seems that Docker Desktop on Windows with the WSL 2 backend has some issues with MariaDB (c.f. [mariadb-docker#331](https://github.com/MariaDB/mariadb-docker/issues/331)) triggered by NexusDashboard +> migrations, so this setup may not work for you. If that is the case, please tell us about your setup in [NexusDashboard#92](https://github.com/DarkflameUniverse/NexusDashboard/issues/92). + You can use the `docker-compose` tool to [setup a MariaDB database](#database-setup), run the Darkflame Server and manage it with [Nexus Dashboard](https://github.com/DarkflameUniverse/NexusDashboard) all at once. For that: From 2f247b1fc9b9bef6e3ae28ffae9ab3606c942a62 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 28 Jan 2024 23:52:59 -0800 Subject: [PATCH 02/50] fix: faction changes not allowing updated targets (#1437) * fix faction change issue fixes an issue where enemies who would have their faction changed would not change aggro targets. Tested that stromling mechs and ronin/horsemen in forbidden valley still aggro on spawn as expected. * use erase remove if --- dGame/Entity.cpp | 32 +++++++++++--------------------- dGame/Entity.h | 2 +- 2 files changed, 12 insertions(+), 22 deletions(-) diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 8b72a80c..0dc0c99a 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -1357,17 +1357,11 @@ void Entity::OnCollisionPhantom(const LWOOBJID otherEntity) { } if (!other->GetIsDead()) { - auto* combat = GetComponent(); - - if (combat != nullptr) { + if (GetComponent() != nullptr) { const auto index = std::find(m_TargetsInPhantom.begin(), m_TargetsInPhantom.end(), otherEntity); if (index != m_TargetsInPhantom.end()) return; - const auto valid = combat->IsEnemy(otherEntity); - - if (!valid) return; - m_TargetsInPhantom.push_back(otherEntity); } } @@ -1992,25 +1986,21 @@ void Entity::SetNetworkId(const uint16_t id) { m_NetworkID = id; } -std::vector& Entity::GetTargetsInPhantom() { - std::vector valid; - +std::vector Entity::GetTargetsInPhantom() { // Clean up invalid targets, like disconnected players - for (auto i = 0u; i < m_TargetsInPhantom.size(); ++i) { - const auto id = m_TargetsInPhantom.at(i); + m_TargetsInPhantom.erase(std::remove_if(m_TargetsInPhantom.begin(), m_TargetsInPhantom.end(), [](const LWOOBJID id) { + return !Game::entityManager->GetEntity(id); + }), m_TargetsInPhantom.end()); - auto* entity = Game::entityManager->GetEntity(id); + std::vector enemies; + for (const auto id : m_TargetsInPhantom) { + auto* combat = GetComponent(); + if (!combat || !combat->IsEnemy(id)) continue; - if (entity == nullptr) { - continue; - } - - valid.push_back(id); + enemies.push_back(id); } - m_TargetsInPhantom = valid; - - return m_TargetsInPhantom; + return enemies; } void Entity::SendNetworkVar(const std::string& data, const SystemAddress& sysAddr) { diff --git a/dGame/Entity.h b/dGame/Entity.h index 36621d5c..c0a546d3 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -293,7 +293,7 @@ public: /* * Collision */ - std::vector& GetTargetsInPhantom(); + std::vector GetTargetsInPhantom(); Entity* GetScheduledKiller() { return m_ScheduleKiller; } From a0d51e21ca955d17b16e7efea7f3072190e9ecc5 Mon Sep 17 00:00:00 2001 From: jadebenn Date: Mon, 29 Jan 2024 01:53:12 -0600 Subject: [PATCH 03/50] refactor: allow usage of NiPoint3 and NiQuaternion in constexpr context (#1414) * allow usage of NiPoint3 and NiQuaternion in constexpr context * removed .cpp files entirely * moving circular dependency circumvention stuff to an .inl file * real world usage!!!!! * reverting weird branch cross-pollination * removing more weird branch cross-pollination * remove comment * added inverse header guard to inl file * Update NiPoint3.inl * trying different constructor syntax * reorganize into .inl files for readability * uncomment include * moved non-constexpr definitions to cpp file * moved static definitions back to inl files * testing fix * moved constants into seperate namespace * Undo change in build-and-test.yml * nodiscard --- dCommon/NiPoint3.cpp | 232 +----------------- dCommon/NiPoint3.h | 113 +++++---- dCommon/NiPoint3.inl | 196 +++++++++++++++ dCommon/NiQuaternion.cpp | 101 +------- dCommon/NiQuaternion.h | 75 +++--- dCommon/NiQuaternion.inl | 75 ++++++ dCommon/PositionUpdate.h | 12 +- dGame/Character.cpp | 4 +- dGame/Entity.cpp | 20 +- dGame/Entity.h | 4 +- dGame/dBehaviors/ProjectileAttackBehavior.cpp | 2 +- dGame/dComponents/BaseCombatAIComponent.cpp | 2 +- dGame/dComponents/BuildBorderComponent.cpp | 2 +- dGame/dComponents/GhostComponent.cpp | 4 +- .../HavokVehiclePhysicsComponent.cpp | 4 +- dGame/dComponents/InventoryComponent.cpp | 2 +- dGame/dComponents/MovementAIComponent.cpp | 6 +- dGame/dComponents/PetComponent.cpp | 32 +-- dGame/dComponents/PhantomPhysicsComponent.cpp | 2 +- dGame/dComponents/PhysicsComponent.cpp | 4 +- .../PropertyManagementComponent.cpp | 6 +- dGame/dComponents/QuickBuildComponent.cpp | 4 +- dGame/dComponents/QuickBuildComponent.h | 2 +- dGame/dComponents/RacingControlComponent.cpp | 6 +- dGame/dComponents/SimplePhysicsComponent.h | 4 +- dGame/dComponents/TriggerComponent.cpp | 8 +- dGame/dGameMessages/EchoStartSkill.h | 14 +- dGame/dGameMessages/GameMessages.cpp | 48 ++-- dGame/dGameMessages/GameMessages.h | 8 +- dGame/dGameMessages/StartSkill.h | 14 +- .../Enemy/AG/BossSpiderQueenEnemyServer.cpp | 8 +- .../02_server/Map/AG/AgLaserSensorServer.cpp | 2 +- dScripts/02_server/Map/AM/AmDrawBridge.cpp | 2 +- dScripts/02_server/Map/GF/MastTeleport.cpp | 2 +- dScripts/02_server/Pets/PetFromDigServer.cpp | 2 +- dScripts/ai/GF/GfBanana.cpp | 2 +- dScripts/client/ai/PR/CrabServer.cpp | 2 +- dWorldServer/WorldServer.cpp | 4 +- dZoneManager/Spawner.h | 4 +- tests/dCommonTests/TestNiPoint3.cpp | 4 +- tests/dGameTests/GameDependencies.h | 4 +- 41 files changed, 509 insertions(+), 533 deletions(-) create mode 100644 dCommon/NiPoint3.inl create mode 100644 dCommon/NiQuaternion.inl diff --git a/dCommon/NiPoint3.cpp b/dCommon/NiPoint3.cpp index 3394deb7..b8546fdd 100644 --- a/dCommon/NiPoint3.cpp +++ b/dCommon/NiPoint3.cpp @@ -1,210 +1,24 @@ #include "NiPoint3.h" -#include "NiQuaternion.h" // C++ #include -// Static Variables -const NiPoint3 NiPoint3::ZERO(0.0f, 0.0f, 0.0f); -const NiPoint3 NiPoint3::UNIT_X(1.0f, 0.0f, 0.0f); -const NiPoint3 NiPoint3::UNIT_Y(0.0f, 1.0f, 0.0f); -const NiPoint3 NiPoint3::UNIT_Z(0.0f, 0.0f, 1.0f); -const NiPoint3 NiPoint3::UNIT_ALL(1.0f, 1.0f, 1.0f); - -//! Initializer -NiPoint3::NiPoint3(void) { - this->x = 0; - this->y = 0; - this->z = 0; -} - -//! Initializer -NiPoint3::NiPoint3(float x, float y, float z) { - this->x = x; - this->y = y; - this->z = z; -} - -//! Copy Constructor -NiPoint3::NiPoint3(const NiPoint3& point) { - this->x = point.x; - this->y = point.y; - this->z = point.z; -} - -//! Destructor -NiPoint3::~NiPoint3(void) {} - -// MARK: Getters / Setters - -//! Gets the X coordinate -float NiPoint3::GetX(void) const { - return this->x; -} - -//! Sets the X coordinate -void NiPoint3::SetX(float x) { - this->x = x; -} - -//! Gets the Y coordinate -float NiPoint3::GetY(void) const { - return this->y; -} - -//! Sets the Y coordinate -void NiPoint3::SetY(float y) { - this->y = y; -} - -//! Gets the Z coordinate -float NiPoint3::GetZ(void) const { - return this->z; -} - -//! Sets the Z coordinate -void NiPoint3::SetZ(float z) { - this->z = z; -} - -// MARK: Functions +// MARK: Member Functions //! Gets the length of the vector -float NiPoint3::Length(void) const { - return sqrt(x * x + y * y + z * z); -} - -//! Gets the squared length of a vector -float NiPoint3::SquaredLength(void) const { - return (x * x + y * y + z * z); -} - -//! Returns the dot product of the vector dotted with another vector -float NiPoint3::DotProduct(const Vector3& vec) const { - return ((this->x * vec.x) + (this->y * vec.y) + (this->z * vec.z)); -} - -//! Returns the cross product of the vector crossed with another vector -Vector3 NiPoint3::CrossProduct(const Vector3& vec) const { - return Vector3(((this->y * vec.z) - (this->z * vec.y)), - ((this->z * vec.x) - (this->x * vec.z)), - ((this->x * vec.y) - (this->y * vec.x))); +float NiPoint3::Length() const { + return std::sqrt(x * x + y * y + z * z); } //! Unitize the vector -NiPoint3 NiPoint3::Unitize(void) const { +NiPoint3 NiPoint3::Unitize() const { float length = this->Length(); - return length != 0 ? *this / length : NiPoint3::ZERO; + return length != 0 ? *this / length : NiPoint3Constant::ZERO; } - -// MARK: Operators - -//! Operator to check for equality -bool NiPoint3::operator==(const NiPoint3& point) const { - return point.x == this->x && point.y == this->y && point.z == this->z; -} - -//! Operator to check for inequality -bool NiPoint3::operator!=(const NiPoint3& point) const { - return !(*this == point); -} - -//! Operator for subscripting -float& NiPoint3::operator[](int i) { - float* base = &x; - return base[i]; -} - -//! Operator for subscripting -const float& NiPoint3::operator[](int i) const { - const float* base = &x; - return base[i]; -} - -//! Operator for addition of vectors -NiPoint3 NiPoint3::operator+(const NiPoint3& point) const { - return NiPoint3(this->x + point.x, this->y + point.y, this->z + point.z); -} - -//! Operator for addition of vectors -NiPoint3& NiPoint3::operator+=(const NiPoint3& point) { - this->x += point.x; - this->y += point.y; - this->z += point.z; - return *this; -} - -NiPoint3& NiPoint3::operator*=(const float scalar) { - this->x *= scalar; - this->y *= scalar; - this->z *= scalar; - return *this; -} - -//! Operator for subtraction of vectors -NiPoint3 NiPoint3::operator-(const NiPoint3& point) const { - return NiPoint3(this->x - point.x, this->y - point.y, this->z - point.z); -} - -//! Operator for addition of a scalar on all vector components -NiPoint3 NiPoint3::operator+(float fScalar) const { - return NiPoint3(this->x + fScalar, this->y + fScalar, this->z + fScalar); -} - -//! Operator for subtraction of a scalar on all vector components -NiPoint3 NiPoint3::operator-(float fScalar) const { - return NiPoint3(this->x - fScalar, this->y - fScalar, this->z - fScalar); -} - -//! Operator for scalar multiplication of a vector -NiPoint3 NiPoint3::operator*(float fScalar) const { - return NiPoint3(this->x * fScalar, this->y * fScalar, this->z * fScalar); -} - -//! Operator for scalar division of a vector -NiPoint3 NiPoint3::operator/(float fScalar) const { - float retX = this->x != 0 ? this->x / fScalar : 0; - float retY = this->y != 0 ? this->y / fScalar : 0; - float retZ = this->z != 0 ? this->z / fScalar : 0; - return NiPoint3(retX, retY, retZ); -} - - // MARK: Helper Functions -//! Checks to see if the point (or vector) is with an Axis-Aligned Bounding Box -bool NiPoint3::IsWithinAxisAlignedBox(const NiPoint3& minPoint, const NiPoint3& maxPoint) { - if (this->x < minPoint.x) return false; - if (this->x > maxPoint.x) return false; - if (this->y < minPoint.y) return false; - if (this->y > maxPoint.y) return false; - - return (this->z < maxPoint.z && this->z > minPoint.z); -} - -//! Checks to see if the point (or vector) is within a sphere -bool NiPoint3::IsWithinSpehere(const NiPoint3& sphereCenter, float radius) { - Vector3 diffVec = Vector3(x - sphereCenter.GetX(), y - sphereCenter.GetY(), z - sphereCenter.GetZ()); - return (diffVec.SquaredLength() <= (radius * radius)); -} - -NiPoint3 NiPoint3::ClosestPointOnLine(const NiPoint3& a, const NiPoint3& b, const NiPoint3& p) { - if (a == b) return a; - - const auto pa = p - a; - const auto ab = b - a; - - const auto t = pa.DotProduct(ab) / ab.SquaredLength(); - - if (t <= 0.0f) return a; - - if (t >= 1.0f) return b; - - return a + ab * t; -} - float NiPoint3::Angle(const NiPoint3& a, const NiPoint3& b) { const auto dot = a.DotProduct(b); const auto lenA = a.SquaredLength(); @@ -220,15 +34,7 @@ float NiPoint3::Distance(const NiPoint3& a, const NiPoint3& b) { return std::sqrt(dx * dx + dy * dy + dz * dz); } -float NiPoint3::DistanceSquared(const NiPoint3& a, const NiPoint3& b) { - const auto dx = a.x - b.x; - const auto dy = a.y - b.y; - const auto dz = a.z - b.z; - - return dx * dx + dy * dy + dz * dz; -} - -NiPoint3 NiPoint3::MoveTowards(const NiPoint3& current, const NiPoint3& target, float maxDistanceDelta) { +NiPoint3 NiPoint3::MoveTowards(const NiPoint3& current, const NiPoint3& target, const float maxDistanceDelta) { float dx = target.x - current.x; float dy = target.y - current.y; float dz = target.z - current.z; @@ -249,29 +55,3 @@ NiPoint3 NiPoint3::MoveTowards(const NiPoint3& current, const NiPoint3& target, float length = std::sqrt(lengthSquared); return NiPoint3(current.x + dx / length * maxDistanceDelta, current.y + dy / length * maxDistanceDelta, current.z + dz / length * maxDistanceDelta); } - -//This code is yoinked from the MS XNA code, so it should be right, even if it's horrible. -NiPoint3 NiPoint3::RotateByQuaternion(const NiQuaternion& rotation) { - Vector3 vector; - float num12 = rotation.x + rotation.x; - float num2 = rotation.y + rotation.y; - float num = rotation.z + rotation.z; - float num11 = rotation.w * num12; - float num10 = rotation.w * num2; - float num9 = rotation.w * num; - float num8 = rotation.x * num12; - float num7 = rotation.x * num2; - float num6 = rotation.x * num; - float num5 = rotation.y * num2; - float num4 = rotation.y * num; - float num3 = rotation.z * num; - - NiPoint3 value = *this; - float num15 = ((value.x * ((1.0f - num5) - num3)) + (value.y * (num7 - num9))) + (value.z * (num6 + num10)); - float num14 = ((value.x * (num7 + num9)) + (value.y * ((1.0f - num8) - num3))) + (value.z * (num4 - num11)); - float num13 = ((value.x * (num6 - num10)) + (value.y * (num4 + num11))) + (value.z * ((1.0f - num8) - num5)); - vector.x = num15; - vector.y = num14; - vector.z = num13; - return vector; -} diff --git a/dCommon/NiPoint3.h b/dCommon/NiPoint3.h index 44c3c383..00d09083 100644 --- a/dCommon/NiPoint3.h +++ b/dCommon/NiPoint3.h @@ -1,4 +1,5 @@ -#pragma once +#ifndef __NIPOINT3_H__ +#define __NIPOINT3_H__ /*! \file NiPoint3.hpp @@ -12,13 +13,13 @@ typedef NiPoint3 Vector3; //!< The Vector3 class is technically the NiPoin //! A custom class the defines a point in space class NiPoint3 { public: - float x; //!< The x position - float y; //!< The y position - float z; //!< The z position + float x{ 0 }; //!< The x position + float y{ 0 }; //!< The y position + float z{ 0 }; //!< The z position //! Initializer - NiPoint3(void); + constexpr NiPoint3() = default; //! Initializer /*! @@ -26,23 +27,21 @@ public: \param y The y coordinate \param z The z coordinate */ - NiPoint3(float x, float y, float z); + constexpr NiPoint3(const float x, const float y, const float z) noexcept + : x{ x } + , y{ y } + , z{ z } { + } //! Copy Constructor /*! \param point The point to copy */ - NiPoint3(const NiPoint3& point); - - //! Destructor - ~NiPoint3(void); - - // MARK: Constants - static const NiPoint3 ZERO; //!< Point(0, 0, 0) - static const NiPoint3 UNIT_X; //!< Point(1, 0, 0) - static const NiPoint3 UNIT_Y; //!< Point(0, 1, 0) - static const NiPoint3 UNIT_Z; //!< Point(0, 0, 1) - static const NiPoint3 UNIT_ALL; //!< Point(1, 1, 1) + constexpr NiPoint3(const NiPoint3& point) noexcept + : x{ point.x } + , y{ point.y } + , z{ point.z } { + } // MARK: Getters / Setters @@ -50,38 +49,37 @@ public: /*! \return The x coordinate */ - float GetX(void) const; + [[nodiscard]] constexpr float GetX() const noexcept; //! Sets the X coordinate /*! \param x The x coordinate */ - void SetX(float x); + constexpr void SetX(const float x) noexcept; //! Gets the Y coordinate /*! \return The y coordinate */ - float GetY(void) const; + [[nodiscard]] constexpr float GetY() const noexcept; //! Sets the Y coordinate /*! \param y The y coordinate */ - void SetY(float y); + constexpr void SetY(const float y) noexcept; //! Gets the Z coordinate /*! \return The z coordinate */ - float GetZ(void) const; + [[nodiscard]] constexpr float GetZ() const noexcept; //! Sets the Z coordinate /*! \param z The z coordinate */ - void SetZ(float z); - + constexpr void SetZ(const float z) noexcept; // MARK: Member Functions @@ -89,72 +87,70 @@ public: /*! \return The scalar length of the vector */ - float Length(void) const; + [[nodiscard]] float Length() const; //! Gets the squared length of a vector /*! \return The squared length of a vector */ - float SquaredLength(void) const; + [[nodiscard]] constexpr float SquaredLength() const noexcept; //! Returns the dot product of the vector dotted with another vector /*! \param vec The second vector \return The dot product of the two vectors */ - float DotProduct(const Vector3& vec) const; + [[nodiscard]] constexpr float DotProduct(const Vector3& vec) const noexcept; //! Returns the cross product of the vector crossed with another vector /*! \param vec The second vector \return The cross product of the two vectors */ - Vector3 CrossProduct(const Vector3& vec) const; + [[nodiscard]] constexpr Vector3 CrossProduct(const Vector3& vec) const noexcept; //! Unitize the vector /*! \returns The current vector */ - NiPoint3 Unitize(void) const; - + [[nodiscard]] NiPoint3 Unitize() const; // MARK: Operators //! Operator to check for equality - bool operator==(const NiPoint3& point) const; + constexpr bool operator==(const NiPoint3& point) const noexcept; //! Operator to check for inequality - bool operator!=(const NiPoint3& point) const; + constexpr bool operator!=(const NiPoint3& point) const noexcept; //! Operator for subscripting - float& operator[](int i); + constexpr float& operator[](const int i) noexcept; //! Operator for subscripting - const float& operator[](int i) const; + constexpr const float& operator[](const int i) const noexcept; //! Operator for addition of vectors - NiPoint3 operator+(const NiPoint3& point) const; + constexpr NiPoint3 operator+(const NiPoint3& point) const noexcept; //! Operator for addition of vectors - NiPoint3& operator+=(const NiPoint3& point); + constexpr NiPoint3& operator+=(const NiPoint3& point) noexcept; - NiPoint3& operator*=(const float scalar); + constexpr NiPoint3& operator*=(const float scalar) noexcept; //! Operator for subtraction of vectors - NiPoint3 operator-(const NiPoint3& point) const; + constexpr NiPoint3 operator-(const NiPoint3& point) const noexcept; //! Operator for addition of a scalar on all vector components - NiPoint3 operator+(float fScalar) const; + constexpr NiPoint3 operator+(const float fScalar) const noexcept; //! Operator for subtraction of a scalar on all vector components - NiPoint3 operator-(float fScalar) const; + constexpr NiPoint3 operator-(const float fScalar) const noexcept; //! Operator for scalar multiplication of a vector - NiPoint3 operator*(float fScalar) const; + constexpr NiPoint3 operator*(const float fScalar) const noexcept; //! Operator for scalar division of a vector - NiPoint3 operator/(float fScalar) const; - + constexpr NiPoint3 operator/(const float fScalar) const noexcept; // MARK: Helper Functions @@ -164,14 +160,14 @@ public: \param maxPoint The maximum point of the bounding box \return Whether or not this point lies within the box */ - bool IsWithinAxisAlignedBox(const NiPoint3& minPoint, const NiPoint3& maxPoint); + [[nodiscard]] constexpr bool IsWithinAxisAlignedBox(const NiPoint3& minPoint, const NiPoint3& maxPoint) noexcept; //! Checks to see if the point (or vector) is within a sphere /*! \param sphereCenter The sphere center \param radius The radius */ - bool IsWithinSpehere(const NiPoint3& sphereCenter, float radius); + [[nodiscard]] constexpr bool IsWithinSphere(const NiPoint3& sphereCenter, const float radius) noexcept; /*! \param a Start of line @@ -179,15 +175,30 @@ public: \param p Refrence point \return The point of line AB which is closest to P */ - static NiPoint3 ClosestPointOnLine(const NiPoint3& a, const NiPoint3& b, const NiPoint3& p); + [[nodiscard]] static constexpr NiPoint3 ClosestPointOnLine(const NiPoint3& a, const NiPoint3& b, const NiPoint3& p) noexcept; - static float Angle(const NiPoint3& a, const NiPoint3& b); + [[nodiscard]] static float Angle(const NiPoint3& a, const NiPoint3& b); - static float Distance(const NiPoint3& a, const NiPoint3& b); + [[nodiscard]] static float Distance(const NiPoint3& a, const NiPoint3& b); - static float DistanceSquared(const NiPoint3& a, const NiPoint3& b); + [[nodiscard]] static constexpr float DistanceSquared(const NiPoint3& a, const NiPoint3& b) noexcept; - static NiPoint3 MoveTowards(const NiPoint3& current, const NiPoint3& target, float maxDistanceDelta); + [[nodiscard]] static NiPoint3 MoveTowards(const NiPoint3& current, const NiPoint3& target, const float maxDistanceDelta); - NiPoint3 RotateByQuaternion(const NiQuaternion& rotation); + //This code is yoinked from the MS XNA code, so it should be right, even if it's horrible. + [[nodiscard]] constexpr NiPoint3 RotateByQuaternion(const NiQuaternion& rotation) noexcept; }; + +// Static Variables +namespace NiPoint3Constant { + constexpr NiPoint3 ZERO(0.0f, 0.0f, 0.0f); + constexpr NiPoint3 UNIT_X(1.0f, 0.0f, 0.0f); + constexpr NiPoint3 UNIT_Y(0.0f, 1.0f, 0.0f); + constexpr NiPoint3 UNIT_Z(0.0f, 0.0f, 1.0f); + constexpr NiPoint3 UNIT_ALL(1.0f, 1.0f, 1.0f); +} + +// .inl file needed for code organization and to circumvent circular dependency issues +#include "NiPoint3.inl" + +#endif // !__NIPOINT3_H__ diff --git a/dCommon/NiPoint3.inl b/dCommon/NiPoint3.inl new file mode 100644 index 00000000..48aa3ae1 --- /dev/null +++ b/dCommon/NiPoint3.inl @@ -0,0 +1,196 @@ +#pragma once +#ifndef __NIPOINT3_H__ +#error "This should only be included inline in NiPoint3.h: Do not include directly!" +#endif + +#include "NiQuaternion.h" + +// MARK: Getters / Setters + +//! Gets the X coordinate +constexpr float NiPoint3::GetX() const noexcept { + return this->x; +} + +//! Sets the X coordinate +constexpr void NiPoint3::SetX(const float x) noexcept { + this->x = x; +} + +//! Gets the Y coordinate +constexpr float NiPoint3::GetY() const noexcept { + return this->y; +} + +//! Sets the Y coordinate +constexpr void NiPoint3::SetY(const float y) noexcept { + this->y = y; +} + +//! Gets the Z coordinate +constexpr float NiPoint3::GetZ() const noexcept { + return this->z; +} + +//! Sets the Z coordinate +constexpr void NiPoint3::SetZ(const float z) noexcept { + this->z = z; +} + +// MARK: Member Functions + +//! Gets the squared length of a vector +constexpr float NiPoint3::SquaredLength() const noexcept { + return (x * x + y * y + z * z); +} + +//! Returns the dot product of the vector dotted with another vector +constexpr float NiPoint3::DotProduct(const Vector3& vec) const noexcept { + return ((this->x * vec.x) + (this->y * vec.y) + (this->z * vec.z)); +} + +//! Returns the cross product of the vector crossed with another vector +constexpr Vector3 NiPoint3::CrossProduct(const Vector3& vec) const noexcept { + return Vector3(((this->y * vec.z) - (this->z * vec.y)), + ((this->z * vec.x) - (this->x * vec.z)), + ((this->x * vec.y) - (this->y * vec.x))); +} + +// MARK: Operators + +//! Operator to check for equality +constexpr bool NiPoint3::operator==(const NiPoint3& point) const noexcept { + return point.x == this->x && point.y == this->y && point.z == this->z; +} + +//! Operator to check for inequality +constexpr bool NiPoint3::operator!=(const NiPoint3& point) const noexcept { + return !(*this == point); +} + +//! Operator for subscripting +constexpr float& NiPoint3::operator[](const int i) noexcept { + float* base = &x; + return base[i]; +} + +//! Operator for subscripting +constexpr const float& NiPoint3::operator[](const int i) const noexcept { + const float* base = &x; + return base[i]; +} + +//! Operator for addition of vectors +constexpr NiPoint3 NiPoint3::operator+(const NiPoint3& point) const noexcept { + return NiPoint3(this->x + point.x, this->y + point.y, this->z + point.z); +} + +//! Operator for addition of vectors +constexpr NiPoint3& NiPoint3::operator+=(const NiPoint3& point) noexcept { + this->x += point.x; + this->y += point.y; + this->z += point.z; + return *this; +} + +constexpr NiPoint3& NiPoint3::operator*=(const float scalar) noexcept { + this->x *= scalar; + this->y *= scalar; + this->z *= scalar; + return *this; +} + +//! Operator for subtraction of vectors +constexpr NiPoint3 NiPoint3::operator-(const NiPoint3& point) const noexcept { + return NiPoint3(this->x - point.x, this->y - point.y, this->z - point.z); +} + +//! Operator for addition of a scalar on all vector components +constexpr NiPoint3 NiPoint3::operator+(const float fScalar) const noexcept { + return NiPoint3(this->x + fScalar, this->y + fScalar, this->z + fScalar); +} + +//! Operator for subtraction of a scalar on all vector components +constexpr NiPoint3 NiPoint3::operator-(const float fScalar) const noexcept { + return NiPoint3(this->x - fScalar, this->y - fScalar, this->z - fScalar); +} + +//! Operator for scalar multiplication of a vector +constexpr NiPoint3 NiPoint3::operator*(const float fScalar) const noexcept { + return NiPoint3(this->x * fScalar, this->y * fScalar, this->z * fScalar); +} + +//! Operator for scalar division of a vector +constexpr NiPoint3 NiPoint3::operator/(const float fScalar) const noexcept { + float retX = this->x != 0 ? this->x / fScalar : 0; + float retY = this->y != 0 ? this->y / fScalar : 0; + float retZ = this->z != 0 ? this->z / fScalar : 0; + return NiPoint3(retX, retY, retZ); +} + +// MARK: Helper Functions + +//! Checks to see if the point (or vector) is with an Axis-Aligned Bounding Box +constexpr bool NiPoint3::IsWithinAxisAlignedBox(const NiPoint3& minPoint, const NiPoint3& maxPoint) noexcept { + if (this->x < minPoint.x) return false; + if (this->x > maxPoint.x) return false; + if (this->y < minPoint.y) return false; + if (this->y > maxPoint.y) return false; + + return (this->z < maxPoint.z && this->z > minPoint.z); +} + +//! Checks to see if the point (or vector) is within a sphere +constexpr bool NiPoint3::IsWithinSphere(const NiPoint3& sphereCenter, const float radius) noexcept { + Vector3 diffVec = Vector3(x - sphereCenter.GetX(), y - sphereCenter.GetY(), z - sphereCenter.GetZ()); + return (diffVec.SquaredLength() <= (radius * radius)); +} + +constexpr NiPoint3 NiPoint3::ClosestPointOnLine(const NiPoint3& a, const NiPoint3& b, const NiPoint3& p) noexcept { + if (a == b) return a; + + const auto pa = p - a; + const auto ab = b - a; + + const auto t = pa.DotProduct(ab) / ab.SquaredLength(); + + if (t <= 0.0f) return a; + + if (t >= 1.0f) return b; + + return a + ab * t; +} + +constexpr float NiPoint3::DistanceSquared(const NiPoint3& a, const NiPoint3& b) noexcept { + const auto dx = a.x - b.x; + const auto dy = a.y - b.y; + const auto dz = a.z - b.z; + + return dx * dx + dy * dy + dz * dz; +} + +//This code is yoinked from the MS XNA code, so it should be right, even if it's horrible. +constexpr NiPoint3 NiPoint3::RotateByQuaternion(const NiQuaternion& rotation) noexcept { + Vector3 vector; + float num12 = rotation.x + rotation.x; + float num2 = rotation.y + rotation.y; + float num = rotation.z + rotation.z; + float num11 = rotation.w * num12; + float num10 = rotation.w * num2; + float num9 = rotation.w * num; + float num8 = rotation.x * num12; + float num7 = rotation.x * num2; + float num6 = rotation.x * num; + float num5 = rotation.y * num2; + float num4 = rotation.y * num; + float num3 = rotation.z * num; + + NiPoint3 value = *this; + float num15 = ((value.x * ((1.0f - num5) - num3)) + (value.y * (num7 - num9))) + (value.z * (num6 + num10)); + float num14 = ((value.x * (num7 + num9)) + (value.y * ((1.0f - num8) - num3))) + (value.z * (num4 - num11)); + float num13 = ((value.x * (num6 - num10)) + (value.y * (num4 + num11))) + (value.z * ((1.0f - num8) - num5)); + vector.x = num15; + vector.y = num14; + vector.z = num13; + return vector; +} diff --git a/dCommon/NiQuaternion.cpp b/dCommon/NiQuaternion.cpp index 33c5c976..b12d3991 100644 --- a/dCommon/NiQuaternion.cpp +++ b/dCommon/NiQuaternion.cpp @@ -3,89 +3,8 @@ // C++ #include -// Static Variables -const NiQuaternion NiQuaternion::IDENTITY(1, 0, 0, 0); - -//! The initializer -NiQuaternion::NiQuaternion(void) { - this->w = 1; - this->x = 0; - this->y = 0; - this->z = 0; -} - -//! The initializer -NiQuaternion::NiQuaternion(float w, float x, float y, float z) { - this->w = w; - this->x = x; - this->y = y; - this->z = z; -} - -//! Destructor -NiQuaternion::~NiQuaternion(void) {} - - -// MARK: Setters / Getters - -//! Gets the W coordinate -float NiQuaternion::GetW(void) const { - return this->w; -} - -//! Sets the W coordinate -void NiQuaternion::SetW(float w) { - this->w = w; -} - -//! Gets the X coordinate -float NiQuaternion::GetX(void) const { - return this->x; -} - -//! Sets the X coordinate -void NiQuaternion::SetX(float x) { - this->x = x; -} - -//! Gets the Y coordinate -float NiQuaternion::GetY(void) const { - return this->y; -} - -//! Sets the Y coordinate -void NiQuaternion::SetY(float y) { - this->y = y; -} - -//! Gets the Z coordinate -float NiQuaternion::GetZ(void) const { - return this->z; -} - -//! Sets the Z coordinate -void NiQuaternion::SetZ(float z) { - this->z = z; -} - - // MARK: Member Functions -//! Returns the forward vector from the quaternion -Vector3 NiQuaternion::GetForwardVector(void) const { - return Vector3(2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x * x + y * y)); -} - -//! Returns the up vector from the quaternion -Vector3 NiQuaternion::GetUpVector(void) const { - return Vector3(2 * (x * y - w * z), 1 - 2 * (x * x + z * z), 2 * (y * z + w * x)); -} - -//! Returns the right vector from the quaternion -Vector3 NiQuaternion::GetRightVector(void) const { - return Vector3(1 - 2 * (y * y + z * z), 2 * (x * y + w * z), 2 * (x * z - w * y)); -} - Vector3 NiQuaternion::GetEulerAngles() const { Vector3 angles; @@ -111,22 +30,9 @@ Vector3 NiQuaternion::GetEulerAngles() const { return angles; } -// MARK: Operators - -//! Operator to check for equality -bool NiQuaternion::operator==(const NiQuaternion& rot) const { - return rot.x == this->x && rot.y == this->y && rot.z == this->z && rot.w == this->w; -} - -//! Operator to check for inequality -bool NiQuaternion::operator!=(const NiQuaternion& rot) const { - return !(*this == rot); -} - - // MARK: Helper Functions -//! Look from a specific point in space to another point in space +//! Look from a specific point in space to another point in space (Y-locked) NiQuaternion NiQuaternion::LookAt(const NiPoint3& sourcePoint, const NiPoint3& destPoint) { //To make sure we don't orient around the X/Z axis: NiPoint3 source = sourcePoint; @@ -136,7 +42,7 @@ NiQuaternion NiQuaternion::LookAt(const NiPoint3& sourcePoint, const NiPoint3& d NiPoint3 forwardVector = NiPoint3(dest - source).Unitize(); - NiPoint3 posZ = NiPoint3::UNIT_Z; + NiPoint3 posZ = NiPoint3Constant::UNIT_Z; NiPoint3 vecA = posZ.CrossProduct(forwardVector).Unitize(); float dot = posZ.DotProduct(forwardVector); @@ -148,10 +54,11 @@ NiQuaternion NiQuaternion::LookAt(const NiPoint3& sourcePoint, const NiPoint3& d return NiQuaternion::CreateFromAxisAngle(vecA, rotAngle); } +//! Look from a specific point in space to another point in space NiQuaternion NiQuaternion::LookAtUnlocked(const NiPoint3& sourcePoint, const NiPoint3& destPoint) { NiPoint3 forwardVector = NiPoint3(destPoint - sourcePoint).Unitize(); - NiPoint3 posZ = NiPoint3::UNIT_Z; + NiPoint3 posZ = NiPoint3Constant::UNIT_Z; NiPoint3 vecA = posZ.CrossProduct(forwardVector).Unitize(); float dot = posZ.DotProduct(forwardVector); diff --git a/dCommon/NiQuaternion.h b/dCommon/NiQuaternion.h index b7d60f4e..482b86fa 100644 --- a/dCommon/NiQuaternion.h +++ b/dCommon/NiQuaternion.h @@ -1,4 +1,5 @@ -#pragma once +#ifndef __NIQUATERNION_H__ +#define __NIQUATERNION_H__ // Custom Classes #include "NiPoint3.h" @@ -14,14 +15,14 @@ typedef NiQuaternion Quaternion; //!< A typedef for a shorthand version o //! A class that defines a rotation in space class NiQuaternion { public: - float w; //!< The w coordinate - float x; //!< The x coordinate - float y; //!< The y coordinate - float z; //!< The z coordinate + float w{ 1 }; //!< The w coordinate + float x{ 0 }; //!< The x coordinate + float y{ 0 }; //!< The y coordinate + float z{ 0 }; //!< The z coordinate //! The initializer - NiQuaternion(void); + constexpr NiQuaternion() = default; //! The initializer /*! @@ -30,13 +31,12 @@ public: \param y The y coordinate \param z The z coordinate */ - NiQuaternion(float w, float x, float y, float z); - - //! Destructor - ~NiQuaternion(void); - - // MARK: Constants - static const NiQuaternion IDENTITY; //!< Quaternion(1, 0, 0, 0) + constexpr NiQuaternion(const float w, const float x, const float y, const float z) noexcept + : w{ w } + , x{ x } + , y{ y } + , z{ z } { + } // MARK: Setters / Getters @@ -44,50 +44,49 @@ public: /*! \return The w coordinate */ - float GetW(void) const; + [[nodiscard]] constexpr float GetW() const noexcept; //! Sets the W coordinate /*! \param w The w coordinate */ - void SetW(float w); + constexpr void SetW(const float w) noexcept; //! Gets the X coordinate /*! \return The x coordinate */ - float GetX(void) const; + [[nodiscard]] constexpr float GetX() const noexcept; //! Sets the X coordinate /*! \param x The x coordinate */ - void SetX(float x); + constexpr void SetX(const float x) noexcept; //! Gets the Y coordinate /*! \return The y coordinate */ - float GetY(void) const; + [[nodiscard]] constexpr float GetY() const noexcept; //! Sets the Y coordinate /*! \param y The y coordinate */ - void SetY(float y); + constexpr void SetY(const float y) noexcept; //! Gets the Z coordinate /*! \return The z coordinate */ - float GetZ(void) const; + [[nodiscard]] constexpr float GetZ() const noexcept; //! Sets the Z coordinate /*! \param z The z coordinate */ - void SetZ(float z); - + constexpr void SetZ(const float z) noexcept; // MARK: Member Functions @@ -95,31 +94,29 @@ public: /*! \return The forward vector of the quaternion */ - Vector3 GetForwardVector(void) const; + [[nodiscard]] constexpr Vector3 GetForwardVector() const noexcept; //! Returns the up vector from the quaternion /*! \return The up vector fo the quaternion */ - Vector3 GetUpVector(void) const; + [[nodiscard]] constexpr Vector3 GetUpVector() const noexcept; //! Returns the right vector from the quaternion /*! \return The right vector of the quaternion */ - Vector3 GetRightVector(void) const; - - Vector3 GetEulerAngles() const; + [[nodiscard]] constexpr Vector3 GetRightVector() const noexcept; + [[nodiscard]] Vector3 GetEulerAngles() const; // MARK: Operators //! Operator to check for equality - bool operator==(const NiQuaternion& rot) const; + constexpr bool operator==(const NiQuaternion& rot) const noexcept; //! Operator to check for inequality - bool operator!=(const NiQuaternion& rot) const; - + constexpr bool operator!=(const NiQuaternion& rot) const noexcept; // MARK: Helper Functions @@ -129,7 +126,7 @@ public: \param destPoint The destination location \return The Quaternion with the rotation towards the destination */ - static NiQuaternion LookAt(const NiPoint3& sourcePoint, const NiPoint3& destPoint); + [[nodiscard]] static NiQuaternion LookAt(const NiPoint3& sourcePoint, const NiPoint3& destPoint); //! Look from a specific point in space to another point in space /*! @@ -137,7 +134,7 @@ public: \param destPoint The destination location \return The Quaternion with the rotation towards the destination */ - static NiQuaternion LookAtUnlocked(const NiPoint3& sourcePoint, const NiPoint3& destPoint); + [[nodiscard]] static NiQuaternion LookAtUnlocked(const NiPoint3& sourcePoint, const NiPoint3& destPoint); //! Creates a Quaternion from a specific axis and angle relative to that axis /*! @@ -145,7 +142,17 @@ public: \param angle The angle relative to this axis \return A quaternion created from the axis and angle */ - static NiQuaternion CreateFromAxisAngle(const Vector3& axis, float angle); + [[nodiscard]] static NiQuaternion CreateFromAxisAngle(const Vector3& axis, float angle); - static NiQuaternion FromEulerAngles(const NiPoint3& eulerAngles); + [[nodiscard]] static NiQuaternion FromEulerAngles(const NiPoint3& eulerAngles); }; + +// Static Variables +namespace NiQuaternionConstant { + constexpr NiQuaternion IDENTITY(1, 0, 0, 0); +} + +// Include constexpr and inline function definitions in a seperate file for readability +#include "NiQuaternion.inl" + +#endif // !__NIQUATERNION_H__ diff --git a/dCommon/NiQuaternion.inl b/dCommon/NiQuaternion.inl new file mode 100644 index 00000000..9ed84ffc --- /dev/null +++ b/dCommon/NiQuaternion.inl @@ -0,0 +1,75 @@ +#pragma once +#ifndef __NIQUATERNION_H__ +#error "This should only be included inline in NiQuaternion.h: Do not include directly!" +#endif + +// MARK: Setters / Getters + +//! Gets the W coordinate +constexpr float NiQuaternion::GetW() const noexcept { + return this->w; +} + +//! Sets the W coordinate +constexpr void NiQuaternion::SetW(const float w) noexcept { + this->w = w; +} + +//! Gets the X coordinate +constexpr float NiQuaternion::GetX() const noexcept { + return this->x; +} + +//! Sets the X coordinate +constexpr void NiQuaternion::SetX(const float x) noexcept { + this->x = x; +} + +//! Gets the Y coordinate +constexpr float NiQuaternion::GetY() const noexcept { + return this->y; +} + +//! Sets the Y coordinate +constexpr void NiQuaternion::SetY(const float y) noexcept { + this->y = y; +} + +//! Gets the Z coordinate +constexpr float NiQuaternion::GetZ() const noexcept { + return this->z; +} + +//! Sets the Z coordinate +constexpr void NiQuaternion::SetZ(const float z) noexcept { + this->z = z; +} + +// MARK: Member Functions + +//! Returns the forward vector from the quaternion +constexpr Vector3 NiQuaternion::GetForwardVector() const noexcept { + return Vector3(2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x * x + y * y)); +} + +//! Returns the up vector from the quaternion +constexpr Vector3 NiQuaternion::GetUpVector() const noexcept { + return Vector3(2 * (x * y - w * z), 1 - 2 * (x * x + z * z), 2 * (y * z + w * x)); +} + +//! Returns the right vector from the quaternion +constexpr Vector3 NiQuaternion::GetRightVector() const noexcept { + return Vector3(1 - 2 * (y * y + z * z), 2 * (x * y + w * z), 2 * (x * z - w * y)); +} + +// MARK: Operators + +//! Operator to check for equality +constexpr bool NiQuaternion::operator==(const NiQuaternion& rot) const noexcept { + return rot.x == this->x && rot.y == this->y && rot.z == this->z && rot.w == this->w; +} + +//! Operator to check for inequality +constexpr bool NiQuaternion::operator!=(const NiQuaternion& rot) const noexcept { + return !(*this == rot); +} diff --git a/dCommon/PositionUpdate.h b/dCommon/PositionUpdate.h index 1b84e371..4d591a97 100644 --- a/dCommon/PositionUpdate.h +++ b/dCommon/PositionUpdate.h @@ -32,17 +32,17 @@ struct RemoteInputInfo { struct LocalSpaceInfo { LWOOBJID objectId = LWOOBJID_EMPTY; - NiPoint3 position = NiPoint3::ZERO; - NiPoint3 linearVelocity = NiPoint3::ZERO; + NiPoint3 position = NiPoint3Constant::ZERO; + NiPoint3 linearVelocity = NiPoint3Constant::ZERO; }; struct PositionUpdate { - NiPoint3 position = NiPoint3::ZERO; - NiQuaternion rotation = NiQuaternion::IDENTITY; + NiPoint3 position = NiPoint3Constant::ZERO; + NiQuaternion rotation = NiQuaternionConstant::IDENTITY; bool onGround = false; bool onRail = false; - NiPoint3 velocity = NiPoint3::ZERO; - NiPoint3 angularVelocity = NiPoint3::ZERO; + NiPoint3 velocity = NiPoint3Constant::ZERO; + NiPoint3 angularVelocity = NiPoint3Constant::ZERO; LocalSpaceInfo localSpaceInfo; RemoteInputInfo remoteInputInfo; }; diff --git a/dGame/Character.cpp b/dGame/Character.cpp index ee04710a..eab7583f 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -451,7 +451,7 @@ void Character::LoadXmlRespawnCheckpoints() { auto* r = points->FirstChildElement("r"); while (r != nullptr) { int32_t map = 0; - NiPoint3 point = NiPoint3::ZERO; + NiPoint3 point = NiPoint3Constant::ZERO; r->QueryAttribute("w", &map); r->QueryAttribute("x", &point.x); @@ -513,7 +513,7 @@ void Character::SetRespawnPoint(LWOMAPID map, const NiPoint3& point) { const NiPoint3& Character::GetRespawnPoint(LWOMAPID map) const { const auto& pair = m_WorldRespawnCheckpoints.find(map); - if (pair == m_WorldRespawnCheckpoints.end()) return NiPoint3::ZERO; + if (pair == m_WorldRespawnCheckpoints.end()) return NiPoint3Constant::ZERO; return pair->second; } diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 0dc0c99a..89b925c6 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -1857,7 +1857,7 @@ const NiPoint3& Entity::GetPosition() const { return vehicel->GetPosition(); } - return NiPoint3::ZERO; + return NiPoint3Constant::ZERO; } const NiQuaternion& Entity::GetRotation() const { @@ -1885,7 +1885,7 @@ const NiQuaternion& Entity::GetRotation() const { return vehicel->GetRotation(); } - return NiQuaternion::IDENTITY; + return NiQuaternionConstant::IDENTITY; } void Entity::SetPosition(const NiPoint3& position) { @@ -2086,9 +2086,9 @@ void Entity::ProcessPositionUpdate(PositionUpdate& update) { havokVehiclePhysicsComponent->SetIsOnGround(update.onGround); havokVehiclePhysicsComponent->SetIsOnRail(update.onRail); havokVehiclePhysicsComponent->SetVelocity(update.velocity); - havokVehiclePhysicsComponent->SetDirtyVelocity(update.velocity != NiPoint3::ZERO); + havokVehiclePhysicsComponent->SetDirtyVelocity(update.velocity != NiPoint3Constant::ZERO); havokVehiclePhysicsComponent->SetAngularVelocity(update.angularVelocity); - havokVehiclePhysicsComponent->SetDirtyAngularVelocity(update.angularVelocity != NiPoint3::ZERO); + havokVehiclePhysicsComponent->SetDirtyAngularVelocity(update.angularVelocity != NiPoint3Constant::ZERO); havokVehiclePhysicsComponent->SetRemoteInputInfo(update.remoteInputInfo); } else { // Need to get the mount's controllable physics @@ -2099,17 +2099,17 @@ void Entity::ProcessPositionUpdate(PositionUpdate& update) { possessedControllablePhysicsComponent->SetIsOnGround(update.onGround); possessedControllablePhysicsComponent->SetIsOnRail(update.onRail); possessedControllablePhysicsComponent->SetVelocity(update.velocity); - possessedControllablePhysicsComponent->SetDirtyVelocity(update.velocity != NiPoint3::ZERO); + possessedControllablePhysicsComponent->SetDirtyVelocity(update.velocity != NiPoint3Constant::ZERO); possessedControllablePhysicsComponent->SetAngularVelocity(update.angularVelocity); - possessedControllablePhysicsComponent->SetDirtyAngularVelocity(update.angularVelocity != NiPoint3::ZERO); + possessedControllablePhysicsComponent->SetDirtyAngularVelocity(update.angularVelocity != NiPoint3Constant::ZERO); } Game::entityManager->SerializeEntity(possassableEntity); } } if (!updateChar) { - update.velocity = NiPoint3::ZERO; - update.angularVelocity = NiPoint3::ZERO; + update.velocity = NiPoint3Constant::ZERO; + update.angularVelocity = NiPoint3Constant::ZERO; } // Handle statistics @@ -2123,9 +2123,9 @@ void Entity::ProcessPositionUpdate(PositionUpdate& update) { controllablePhysicsComponent->SetIsOnGround(update.onGround); controllablePhysicsComponent->SetIsOnRail(update.onRail); controllablePhysicsComponent->SetVelocity(update.velocity); - controllablePhysicsComponent->SetDirtyVelocity(update.velocity != NiPoint3::ZERO); + controllablePhysicsComponent->SetDirtyVelocity(update.velocity != NiPoint3Constant::ZERO); controllablePhysicsComponent->SetAngularVelocity(update.angularVelocity); - controllablePhysicsComponent->SetDirtyAngularVelocity(update.angularVelocity != NiPoint3::ZERO); + controllablePhysicsComponent->SetDirtyAngularVelocity(update.angularVelocity != NiPoint3Constant::ZERO); auto* ghostComponent = GetComponent(); if (ghostComponent) ghostComponent->SetGhostReferencePoint(update.position); diff --git a/dGame/Entity.h b/dGame/Entity.h index c0a546d3..3074842a 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -229,8 +229,8 @@ public: void TriggerEvent(eTriggerEventType event, Entity* optionalTarget = nullptr); void ScheduleDestructionAfterUpdate() { m_ShouldDestroyAfterUpdate = true; } - virtual const NiPoint3& GetRespawnPosition() const { return NiPoint3::ZERO; } - virtual const NiQuaternion& GetRespawnRotation() const { return NiQuaternion::IDENTITY; } + virtual const NiPoint3& GetRespawnPosition() const { return NiPoint3Constant::ZERO; } + virtual const NiQuaternion& GetRespawnRotation() const { return NiQuaternionConstant::IDENTITY; } void Sleep(); void Wake(); diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.cpp b/dGame/dBehaviors/ProjectileAttackBehavior.cpp index 732ff186..504afc69 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.cpp +++ b/dGame/dBehaviors/ProjectileAttackBehavior.cpp @@ -33,7 +33,7 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea } if (m_useMouseposit && !branch.isSync) { - NiPoint3 targetPosition = NiPoint3::ZERO; + NiPoint3 targetPosition = NiPoint3Constant::ZERO; if (!bitStream->Read(targetPosition)) { LOG("Unable to read targetPosition from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); return; diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 11dff20f..21909d5f 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -185,7 +185,7 @@ void BaseCombatAIComponent::Update(const float deltaTime) { bool stunnedThisFrame = m_Stunned; CalculateCombat(deltaTime); // Putting this here for now - if (m_StartPosition == NiPoint3::ZERO) { + if (m_StartPosition == NiPoint3Constant::ZERO) { m_StartPosition = m_Parent->GetPosition(); } diff --git a/dGame/dComponents/BuildBorderComponent.cpp b/dGame/dComponents/BuildBorderComponent.cpp index 9e392e69..066a8c74 100644 --- a/dGame/dComponents/BuildBorderComponent.cpp +++ b/dGame/dComponents/BuildBorderComponent.cpp @@ -56,7 +56,7 @@ void BuildBorderComponent::OnUse(Entity* originator) { 4, 0, -1, - NiPoint3::ZERO, + NiPoint3Constant::ZERO, 0 ); } else { diff --git a/dGame/dComponents/GhostComponent.cpp b/dGame/dComponents/GhostComponent.cpp index 2978c912..db12ce4d 100644 --- a/dGame/dComponents/GhostComponent.cpp +++ b/dGame/dComponents/GhostComponent.cpp @@ -1,8 +1,8 @@ #include "GhostComponent.h" GhostComponent::GhostComponent(Entity* parent) : Component(parent) { - m_GhostReferencePoint = NiPoint3::ZERO; - m_GhostOverridePoint = NiPoint3::ZERO; + m_GhostReferencePoint = NiPoint3Constant::ZERO; + m_GhostOverridePoint = NiPoint3Constant::ZERO; m_GhostOverride = false; } diff --git a/dGame/dComponents/HavokVehiclePhysicsComponent.cpp b/dGame/dComponents/HavokVehiclePhysicsComponent.cpp index 62e49a56..8c8e14fe 100644 --- a/dGame/dComponents/HavokVehiclePhysicsComponent.cpp +++ b/dGame/dComponents/HavokVehiclePhysicsComponent.cpp @@ -2,8 +2,8 @@ #include "EntityManager.h" HavokVehiclePhysicsComponent::HavokVehiclePhysicsComponent(Entity* parent) : PhysicsComponent(parent) { - m_Velocity = NiPoint3::ZERO; - m_AngularVelocity = NiPoint3::ZERO; + m_Velocity = NiPoint3Constant::ZERO; + m_AngularVelocity = NiPoint3Constant::ZERO; m_IsOnGround = true; m_IsOnRail = false; m_DirtyPosition = true; diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 23d5c163..5e6af885 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -1223,7 +1223,7 @@ void InventoryComponent::SpawnPet(Item* item) { EntityInfo info{}; info.lot = item->GetLot(); info.pos = m_Parent->GetPosition(); - info.rot = NiQuaternion::IDENTITY; + info.rot = NiQuaternionConstant::IDENTITY; info.spawnerID = m_Parent->GetObjectID(); auto* pet = Game::entityManager->CreateEntity(info); diff --git a/dGame/dComponents/MovementAIComponent.cpp b/dGame/dComponents/MovementAIComponent.cpp index 25cafc45..1332fd07 100644 --- a/dGame/dComponents/MovementAIComponent.cpp +++ b/dGame/dComponents/MovementAIComponent.cpp @@ -43,7 +43,7 @@ MovementAIComponent::MovementAIComponent(Entity* parent, MovementAIInfo info) : m_NextWaypoint = m_Parent->GetPosition(); m_Acceleration = 0.4f; m_PullingToPoint = false; - m_PullPoint = NiPoint3::ZERO; + m_PullPoint = NiPoint3Constant::ZERO; m_HaltDistance = 0; m_TimeToTravel = 0; m_TimeTravelled = 0; @@ -88,7 +88,7 @@ void MovementAIComponent::Update(const float deltaTime) { SetPosition(source); - NiPoint3 velocity = NiPoint3::ZERO; + NiPoint3 velocity = NiPoint3Constant::ZERO; if (m_Acceleration > 0 && m_BaseSpeed > 0 && AdvanceWaypointIndex()) // Do we have another waypoint to seek? { @@ -203,7 +203,7 @@ void MovementAIComponent::Stop() { SetPosition(ApproximateLocation()); - SetVelocity(NiPoint3::ZERO); + SetVelocity(NiPoint3Constant::ZERO); m_TimeToTravel = 0; m_TimeTravelled = 0; diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 7e515905..0c377ac7 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -84,7 +84,7 @@ PetComponent::PetComponent(Entity* parentEntity, uint32_t componentId) : Compone m_DatabaseId = LWOOBJID_EMPTY; m_Status = 67108866; // Tamable m_Ability = ePetAbilityType::Invalid; - m_StartPosition = NiPoint3::ZERO; + m_StartPosition = NiPoint3Constant::ZERO; m_MovementAI = nullptr; m_TresureTime = 0; m_Preconditions = nullptr; @@ -312,7 +312,7 @@ void PetComponent::OnUse(Entity* originator) { } void PetComponent::Update(float deltaTime) { - if (m_StartPosition == NiPoint3::ZERO) { + if (m_StartPosition == NiPoint3Constant::ZERO) { m_StartPosition = m_Parent->GetPosition(); } @@ -447,7 +447,7 @@ void PetComponent::Update(float deltaTime) { if (distance < 5 * 5) { m_Interaction = closestTresure->GetObjectID(); - Command(NiPoint3::ZERO, LWOOBJID_EMPTY, 1, 202, true); + Command(NiPoint3Constant::ZERO, LWOOBJID_EMPTY, 1, 202, true); m_TresureTime = 2; } else if (distance < 10 * 10) { @@ -531,7 +531,7 @@ void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) { EntityInfo info{}; info.lot = cached->second.puzzleModelLot; info.pos = position; - info.rot = NiQuaternion::IDENTITY; + info.rot = NiQuaternionConstant::IDENTITY; info.spawnerID = tamer->GetObjectID(); auto* modelEntity = Game::entityManager->CreateEntity(info); @@ -591,9 +591,9 @@ void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) { LWOOBJID_EMPTY, false, ePetTamingNotifyType::NAMINGPET, - NiPoint3::ZERO, - NiPoint3::ZERO, - NiQuaternion::IDENTITY, + NiPoint3Constant::ZERO, + NiPoint3Constant::ZERO, + NiQuaternionConstant::IDENTITY, UNASSIGNED_SYSTEM_ADDRESS ); @@ -671,9 +671,9 @@ void PetComponent::RequestSetPetName(std::u16string name) { m_Tamer, false, ePetTamingNotifyType::SUCCESS, - NiPoint3::ZERO, - NiPoint3::ZERO, - NiQuaternion::IDENTITY, + NiPoint3Constant::ZERO, + NiPoint3Constant::ZERO, + NiQuaternionConstant::IDENTITY, UNASSIGNED_SYSTEM_ADDRESS ); @@ -712,9 +712,9 @@ void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) { m_Tamer, false, ePetTamingNotifyType::QUIT, - NiPoint3::ZERO, - NiPoint3::ZERO, - NiQuaternion::IDENTITY, + NiPoint3Constant::ZERO, + NiPoint3Constant::ZERO, + NiQuaternionConstant::IDENTITY, UNASSIGNED_SYSTEM_ADDRESS ); @@ -763,9 +763,9 @@ void PetComponent::ClientFailTamingMinigame() { m_Tamer, false, ePetTamingNotifyType::FAILED, - NiPoint3::ZERO, - NiPoint3::ZERO, - NiQuaternion::IDENTITY, + NiPoint3Constant::ZERO, + NiPoint3Constant::ZERO, + NiQuaternionConstant::IDENTITY, UNASSIGNED_SYSTEM_ADDRESS ); diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index 45d08b97..217a02fb 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -164,7 +164,7 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : PhysicsCompon dpWorld::AddEntity(m_dpEntity); } else if (info->physicsAsset == "miscellaneous\\misc_phys_640x640.hkx") { // Move this down by 13.521004 units so it is still effectively at the same height as before - m_Position = m_Position - NiPoint3::UNIT_Y * 13.521004f; + m_Position = m_Position - NiPoint3Constant::UNIT_Y * 13.521004f; // TODO Fix physics simulation to do simulation at high velocities due to bullet through paper problem... m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 1638.4f, 13.521004f * 2.0f, 1638.4f); diff --git a/dGame/dComponents/PhysicsComponent.cpp b/dGame/dComponents/PhysicsComponent.cpp index a66c422a..ea57735f 100644 --- a/dGame/dComponents/PhysicsComponent.cpp +++ b/dGame/dComponents/PhysicsComponent.cpp @@ -1,8 +1,8 @@ #include "PhysicsComponent.h" PhysicsComponent::PhysicsComponent(Entity* parent) : Component(parent) { - m_Position = NiPoint3::ZERO; - m_Rotation = NiQuaternion::IDENTITY; + m_Position = NiPoint3Constant::ZERO; + m_Rotation = NiQuaternionConstant::IDENTITY; m_DirtyPosition = false; } diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index dff1e5da..0f6eb5a8 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -297,7 +297,7 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N const auto modelLOT = item->GetLot(); - if (rotation != NiQuaternion::IDENTITY) { + if (rotation != NiQuaternionConstant::IDENTITY) { rotation = { rotation.w, rotation.z, rotation.y, rotation.x }; } @@ -481,7 +481,7 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet GameMessages::SendGetModelsOnProperty(entity->GetObjectID(), GetModels(), UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), NiPoint3::ZERO, LWOOBJID_EMPTY, 16, NiQuaternion::IDENTITY); + GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), NiPoint3Constant::ZERO, LWOOBJID_EMPTY, 16, NiQuaternionConstant::IDENTITY); if (spawner != nullptr) { Game::zoneManager->RemoveSpawner(spawner->m_Info.spawnerID); @@ -534,7 +534,7 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet GameMessages::SendGetModelsOnProperty(entity->GetObjectID(), GetModels(), UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), NiPoint3::ZERO, LWOOBJID_EMPTY, 16, NiQuaternion::IDENTITY); + GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), NiPoint3Constant::ZERO, LWOOBJID_EMPTY, 16, NiQuaternionConstant::IDENTITY); if (spawner != nullptr) { Game::zoneManager->RemoveSpawner(spawner->m_Info.spawnerID); diff --git a/dGame/dComponents/QuickBuildComponent.cpp b/dGame/dComponents/QuickBuildComponent.cpp index b8aec2bd..1e745d8a 100644 --- a/dGame/dComponents/QuickBuildComponent.cpp +++ b/dGame/dComponents/QuickBuildComponent.cpp @@ -253,13 +253,13 @@ void QuickBuildComponent::OnUse(Entity* originator) { } void QuickBuildComponent::SpawnActivator() { - if (!m_SelfActivator || m_ActivatorPosition != NiPoint3::ZERO) { + if (!m_SelfActivator || m_ActivatorPosition != NiPoint3Constant::ZERO) { if (!m_Activator) { EntityInfo info; info.lot = 6604; info.spawnerID = m_Parent->GetObjectID(); - info.pos = m_ActivatorPosition == NiPoint3::ZERO ? m_Parent->GetPosition() : m_ActivatorPosition; + info.pos = m_ActivatorPosition == NiPoint3Constant::ZERO ? m_Parent->GetPosition() : m_ActivatorPosition; m_Activator = Game::entityManager->CreateEntity(info, nullptr, m_Parent); if (m_Activator) { diff --git a/dGame/dComponents/QuickBuildComponent.h b/dGame/dComponents/QuickBuildComponent.h index a6725a81..d989bc51 100644 --- a/dGame/dComponents/QuickBuildComponent.h +++ b/dGame/dComponents/QuickBuildComponent.h @@ -242,7 +242,7 @@ private: /** * The position that the quickbuild activator is spawned at */ - NiPoint3 m_ActivatorPosition = NiPoint3::ZERO; + NiPoint3 m_ActivatorPosition = NiPoint3Constant::ZERO; /** * The entity that represents the quickbuild activator diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index 5e3d81f4..742563cc 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -119,8 +119,8 @@ void RacingControlComponent::LoadPlayerVehicle(Entity* player, GeneralUtils::UTF16ToWTF8(m_PathName)); auto spawnPointEntities = Game::entityManager->GetEntitiesByLOT(4843); - auto startPosition = NiPoint3::ZERO; - auto startRotation = NiQuaternion::IDENTITY; + auto startPosition = NiPoint3Constant::ZERO; + auto startRotation = NiQuaternionConstant::IDENTITY; const std::string placementAsString = std::to_string(positionNumber); for (auto entity : spawnPointEntities) { if (!entity) continue; @@ -818,7 +818,7 @@ void RacingControlComponent::Update(float deltaTime) { // Some offset up to make they don't fall through the terrain on a // respawn, seems to fix itself to the track anyhow - player.respawnPosition = position + NiPoint3::UNIT_Y * 5; + player.respawnPosition = position + NiPoint3Constant::UNIT_Y * 5; player.respawnRotation = vehicle->GetRotation(); player.respawnIndex = respawnIndex; diff --git a/dGame/dComponents/SimplePhysicsComponent.h b/dGame/dComponents/SimplePhysicsComponent.h index 707f8a41..8f92dd95 100644 --- a/dGame/dComponents/SimplePhysicsComponent.h +++ b/dGame/dComponents/SimplePhysicsComponent.h @@ -87,12 +87,12 @@ private: /** * The current velocity of the entity */ - NiPoint3 m_Velocity = NiPoint3::ZERO; + NiPoint3 m_Velocity = NiPoint3Constant::ZERO; /** * The current angular velocity of the entity */ - NiPoint3 m_AngularVelocity = NiPoint3::ZERO; + NiPoint3 m_AngularVelocity = NiPoint3Constant::ZERO; /** * Whether or not the velocity has changed diff --git a/dGame/dComponents/TriggerComponent.cpp b/dGame/dComponents/TriggerComponent.cpp index 6d7ce3dd..6b83ae73 100644 --- a/dGame/dComponents/TriggerComponent.cpp +++ b/dGame/dComponents/TriggerComponent.cpp @@ -218,7 +218,7 @@ void TriggerComponent::HandleMoveObject(Entity* targetEntity, std::vectorGetPosition(); - NiPoint3 offset = NiPoint3::ZERO; + NiPoint3 offset = NiPoint3Constant::ZERO; GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), offset); position += offset; @@ -228,7 +228,7 @@ void TriggerComponent::HandleMoveObject(Entity* targetEntity, std::vector argArray){ if (argArray.size() <= 2) return; - NiPoint3 vector = NiPoint3::ZERO; + NiPoint3 vector = NiPoint3Constant::ZERO; GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), vector); NiQuaternion rotation = NiQuaternion::FromEulerAngles(vector); @@ -246,7 +246,7 @@ void TriggerComponent::HandlePushObject(Entity* targetEntity, std::vectorSetPhysicsEffectActive(true); phantomPhysicsComponent->SetEffectType(ePhysicsEffectType::PUSH); phantomPhysicsComponent->SetDirectionalMultiplier(1); - NiPoint3 direction = NiPoint3::ZERO; + NiPoint3 direction = NiPoint3Constant::ZERO; GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), direction); phantomPhysicsComponent->SetDirection(direction); @@ -382,7 +382,7 @@ void TriggerComponent::HandleSetPhysicsVolumeEffect(Entity* targetEntity, std::v phantomPhysicsComponent->SetEffectType(effectType); phantomPhysicsComponent->SetDirectionalMultiplier(std::stof(argArray.at(1))); if (argArray.size() > 4) { - NiPoint3 direction = NiPoint3::ZERO; + NiPoint3 direction = NiPoint3Constant::ZERO; GeneralUtils::TryParse(argArray.at(2), argArray.at(3), argArray.at(4), direction); phantomPhysicsComponent->SetDirection(direction); } diff --git a/dGame/dGameMessages/EchoStartSkill.h b/dGame/dGameMessages/EchoStartSkill.h index f5dee816..389a81e0 100644 --- a/dGame/dGameMessages/EchoStartSkill.h +++ b/dGame/dGameMessages/EchoStartSkill.h @@ -13,13 +13,13 @@ public: bUsedMouse = false; fCasterLatency = 0.0f; iCastType = 0; - lastClickedPosit = NiPoint3::ZERO; + lastClickedPosit = NiPoint3Constant::ZERO; optionalTargetID = LWOOBJID_EMPTY; - originatorRot = NiQuaternion::IDENTITY; + originatorRot = NiQuaternionConstant::IDENTITY; uiSkillHandle = 0; } - EchoStartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, float _fCasterLatency = 0.0f, int32_t _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternion::IDENTITY, uint32_t _uiSkillHandle = 0) { + EchoStartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, float _fCasterLatency = 0.0f, int32_t _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3Constant::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternionConstant::IDENTITY, uint32_t _uiSkillHandle = 0) { bUsedMouse = _bUsedMouse; fCasterLatency = _fCasterLatency; iCastType = _iCastType; @@ -50,16 +50,16 @@ public: stream->Write(iCastType != 0); if (iCastType != 0) stream->Write(iCastType); - stream->Write(lastClickedPosit != NiPoint3::ZERO); - if (lastClickedPosit != NiPoint3::ZERO) stream->Write(lastClickedPosit); + stream->Write(lastClickedPosit != NiPoint3Constant::ZERO); + if (lastClickedPosit != NiPoint3Constant::ZERO) stream->Write(lastClickedPosit); stream->Write(optionalOriginatorID); stream->Write(optionalTargetID != LWOOBJID_EMPTY); if (optionalTargetID != LWOOBJID_EMPTY) stream->Write(optionalTargetID); - stream->Write(originatorRot != NiQuaternion::IDENTITY); - if (originatorRot != NiQuaternion::IDENTITY) stream->Write(originatorRot); + stream->Write(originatorRot != NiQuaternionConstant::IDENTITY); + if (originatorRot != NiQuaternionConstant::IDENTITY) stream->Write(originatorRot); uint32_t sBitStreamLength = sBitStream.length(); stream->Write(sBitStreamLength); diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 8c935afe..1214c951 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -385,8 +385,8 @@ void GameMessages::SendPlatformResync(Entity* entity, const SystemAddress& sysAd float fIdleTimeElapsed = 0.0f; float fMoveTimeElapsed = 0.0f; float fPercentBetweenPoints = 0.0f; - NiPoint3 ptUnexpectedLocation = NiPoint3::ZERO; - NiQuaternion qUnexpectedRotation = NiQuaternion::IDENTITY; + NiPoint3 ptUnexpectedLocation = NiPoint3Constant::ZERO; + NiQuaternion qUnexpectedRotation = NiQuaternionConstant::IDENTITY; bitStream.Write(bReverse); bitStream.Write(bStopAtDesiredWaypoint); @@ -403,8 +403,8 @@ void GameMessages::SendPlatformResync(Entity* entity, const SystemAddress& sysAd bitStream.Write(ptUnexpectedLocation.y); bitStream.Write(ptUnexpectedLocation.z); - bitStream.Write(qUnexpectedRotation != NiQuaternion::IDENTITY); - if (qUnexpectedRotation != NiQuaternion::IDENTITY) { + bitStream.Write(qUnexpectedRotation != NiQuaternionConstant::IDENTITY); + if (qUnexpectedRotation != NiQuaternionConstant::IDENTITY) { bitStream.Write(qUnexpectedRotation.x); bitStream.Write(qUnexpectedRotation.y); bitStream.Write(qUnexpectedRotation.z); @@ -770,7 +770,7 @@ void GameMessages::SendSetCurrency(Entity* entity, int64_t currency, int lootTyp bitStream.Write(lootType != LOOTTYPE_NONE); if (lootType != LOOTTYPE_NONE) bitStream.Write(lootType); - bitStream.Write(NiPoint3::ZERO); + bitStream.Write(NiPoint3Constant::ZERO); bitStream.Write(sourceLOT != LOT_NULL); if (sourceLOT != LOT_NULL) bitStream.Write(sourceLOT); @@ -1079,7 +1079,7 @@ void GameMessages::SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, entity->RegisterCoinDrop(currency); } - if (spawnPos != NiPoint3::ZERO) { + if (spawnPos != NiPoint3Constant::ZERO) { bUsePosition = true; //Calculate where the loot will go: @@ -1101,8 +1101,8 @@ void GameMessages::SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, bitStream.Write(bUsePosition); - bitStream.Write(finalPosition != NiPoint3::ZERO); - if (finalPosition != NiPoint3::ZERO) bitStream.Write(finalPosition); + bitStream.Write(finalPosition != NiPoint3Constant::ZERO); + if (finalPosition != NiPoint3Constant::ZERO) bitStream.Write(finalPosition); bitStream.Write(currency); bitStream.Write(item); @@ -1110,8 +1110,8 @@ void GameMessages::SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, bitStream.Write(owner); bitStream.Write(sourceID); - bitStream.Write(spawnPos != NiPoint3::ZERO); - if (spawnPos != NiPoint3::ZERO) bitStream.Write(spawnPos); + bitStream.Write(spawnPos != NiPoint3Constant::ZERO); + if (spawnPos != NiPoint3Constant::ZERO) bitStream.Write(spawnPos); auto* team = TeamManager::Instance()->GetTeam(owner); @@ -1170,7 +1170,7 @@ void GameMessages::SendPlayerReachedRespawnCheckpoint(Entity* entity, const NiPo bitStream.Write(position.y); bitStream.Write(position.z); - const bool bIsNotIdentity = rotation != NiQuaternion::IDENTITY; + const bool bIsNotIdentity = rotation != NiQuaternionConstant::IDENTITY; bitStream.Write(bIsNotIdentity); if (bIsNotIdentity) { @@ -1646,8 +1646,8 @@ void GameMessages::SendNotifyClientShootingGalleryScore(LWOOBJID objectId, const void GameMessages::HandleUpdateShootingGalleryRotation(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { float angle = 0.0f; - NiPoint3 facing = NiPoint3::ZERO; - NiPoint3 muzzlePos = NiPoint3::ZERO; + NiPoint3 facing = NiPoint3Constant::ZERO; + NiPoint3 muzzlePos = NiPoint3Constant::ZERO; inStream->Read(angle); inStream->Read(facing); inStream->Read(muzzlePos); @@ -2103,8 +2103,8 @@ void GameMessages::SendPlaceModelResponse(LWOOBJID objectId, const SystemAddress bitStream.Write(objectId); bitStream.Write(eGameMessageType::PLACE_MODEL_RESPONSE); - bitStream.Write(position != NiPoint3::ZERO); - if (position != NiPoint3::ZERO) { + bitStream.Write(position != NiPoint3Constant::ZERO); + if (position != NiPoint3Constant::ZERO) { bitStream.Write(position); } @@ -2118,8 +2118,8 @@ void GameMessages::SendPlaceModelResponse(LWOOBJID objectId, const SystemAddress bitStream.Write(response); } - bitStream.Write(rotation != NiQuaternion::IDENTITY); - if (rotation != NiQuaternion::IDENTITY) { + bitStream.Write(rotation != NiQuaternionConstant::IDENTITY); + if (rotation != NiQuaternionConstant::IDENTITY) { bitStream.Write(response); } @@ -2271,7 +2271,7 @@ void GameMessages::HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entit bool modePaused{}; int modeValue = 1; LWOOBJID playerId{}; - NiPoint3 startPosition = NiPoint3::ZERO; + NiPoint3 startPosition = NiPoint3Constant::ZERO; inStream->Read(start); @@ -2290,7 +2290,7 @@ void GameMessages::HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entit auto* player = Game::entityManager->GetEntity(playerId); - if (startPosition == NiPoint3::ZERO) { + if (startPosition == NiPoint3Constant::ZERO) { startPosition = player->GetPosition(); } @@ -2384,13 +2384,13 @@ void GameMessages::HandlePlacePropertyModel(RakNet::BitStream* inStream, Entity* inStream->Read(model); - PropertyManagementComponent::Instance()->UpdateModelPosition(model, NiPoint3::ZERO, NiQuaternion::IDENTITY); + PropertyManagementComponent::Instance()->UpdateModelPosition(model, NiPoint3Constant::ZERO, NiQuaternionConstant::IDENTITY); } void GameMessages::HandleUpdatePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID model; NiPoint3 position; - NiQuaternion rotation = NiQuaternion::IDENTITY; + NiQuaternion rotation = NiQuaternionConstant::IDENTITY; inStream->Read(model); inStream->Read(position); @@ -2612,7 +2612,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent IPropertyContents::Model model; model.id = newIDL; model.ugcId = blueprintIDSmall; - model.position = NiPoint3::ZERO; + model.position = NiPoint3Constant::ZERO; model.rotation = NiQuaternion(0.0f, 0.0f, 0.0f, 0.0f); model.lot = 14; Database::Get()->InsertNewPropertyModel(propertyId, model, "Objects_14_name"); @@ -3393,7 +3393,7 @@ void GameMessages::SendNotifyPetTamingMinigame(LWOOBJID objectId, LWOOBJID petId bitStream.Write(petsDestPos); bitStream.Write(telePos); - const bool hasDefault = teleRot != NiQuaternion::IDENTITY; + const bool hasDefault = teleRot != NiQuaternionConstant::IDENTITY; bitStream.Write(hasDefault); if (hasDefault) bitStream.Write(teleRot); @@ -4218,7 +4218,7 @@ void GameMessages::HandleVehicleNotifyHitImaginationServer(RakNet::BitStream* in LWOOBJID pickupObjID = LWOOBJID_EMPTY; LWOOBJID pickupSpawnerID = LWOOBJID_EMPTY; int32_t pickupSpawnerIndex = -1; - NiPoint3 vehiclePosition = NiPoint3::ZERO; + NiPoint3 vehiclePosition = NiPoint3Constant::ZERO; if (inStream->ReadBit()) inStream->Read(pickupObjID); if (inStream->ReadBit()) inStream->Read(pickupSpawnerID); diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 68a8471a..a96bbf60 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -55,14 +55,14 @@ namespace GameMessages { const SystemAddress& sysAddr, bool bFirstTime = true, const LWOOBJID& buildAreaID = LWOOBJID_EMPTY, - NiPoint3 buildStartPOS = NiPoint3::ZERO, + NiPoint3 buildStartPOS = NiPoint3Constant::ZERO, int sourceBAG = 0, const LWOOBJID& sourceID = LWOOBJID_EMPTY, LOT sourceLOT = 0, int sourceTYPE = 8, const LWOOBJID& targetID = 0, LOT targetLOT = 0, - NiPoint3 targetPOS = NiPoint3::ZERO, + NiPoint3 targetPOS = NiPoint3Constant::ZERO, int targetTYPE = 0 ); @@ -122,7 +122,7 @@ namespace GameMessages { void SendStop2DAmbientSound(Entity* entity, bool force, std::string audioGUID, bool result = false); void SendPlay2DAmbientSound(Entity* entity, std::string audioGUID, bool result = false); void SendSetNetworkScriptVar(Entity* entity, const SystemAddress& sysAddr, std::string data); - void SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, LOT item, int currency, NiPoint3 spawnPos = NiPoint3::ZERO, int count = 1); + void SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, LOT item, int currency, NiPoint3 spawnPos = NiPoint3Constant::ZERO, int count = 1); void SendSetPlayerControlScheme(Entity* entity, eControlScheme controlScheme); void SendPlayerReachedRespawnCheckpoint(Entity* entity, const NiPoint3& position, const NiQuaternion& rotation); @@ -239,7 +239,7 @@ namespace GameMessages { void SendLockNodeRotation(Entity* entity, std::string nodeName); - void SendSetBuildModeConfirmed(LWOOBJID objectId, const SystemAddress& sysAddr, bool start, bool warnVisitors, bool modePaused, int32_t modeValue, LWOOBJID playerId, NiPoint3 startPos = NiPoint3::ZERO); + void SendSetBuildModeConfirmed(LWOOBJID objectId, const SystemAddress& sysAddr, bool start, bool warnVisitors, bool modePaused, int32_t modeValue, LWOOBJID playerId, NiPoint3 startPos = NiPoint3Constant::ZERO); void SendGetModelsOnProperty(LWOOBJID objectId, std::map models, const SystemAddress& sysAddr); diff --git a/dGame/dGameMessages/StartSkill.h b/dGame/dGameMessages/StartSkill.h index 40bc210f..6b0d267a 100644 --- a/dGame/dGameMessages/StartSkill.h +++ b/dGame/dGameMessages/StartSkill.h @@ -16,13 +16,13 @@ public: consumableItemID = LWOOBJID_EMPTY; fCasterLatency = 0.0f; iCastType = 0; - lastClickedPosit = NiPoint3::ZERO; + lastClickedPosit = NiPoint3Constant::ZERO; optionalTargetID = LWOOBJID_EMPTY; - originatorRot = NiQuaternion::IDENTITY; + originatorRot = NiQuaternionConstant::IDENTITY; uiSkillHandle = 0; } - StartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, LWOOBJID _consumableItemID = LWOOBJID_EMPTY, float _fCasterLatency = 0.0f, int32_t _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternion::IDENTITY, uint32_t _uiSkillHandle = 0) { + StartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, LWOOBJID _consumableItemID = LWOOBJID_EMPTY, float _fCasterLatency = 0.0f, int32_t _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3Constant::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternionConstant::IDENTITY, uint32_t _uiSkillHandle = 0) { bUsedMouse = _bUsedMouse; consumableItemID = _consumableItemID; fCasterLatency = _fCasterLatency; @@ -57,16 +57,16 @@ public: stream->Write(iCastType != 0); if (iCastType != 0) stream->Write(iCastType); - stream->Write(lastClickedPosit != NiPoint3::ZERO); - if (lastClickedPosit != NiPoint3::ZERO) stream->Write(lastClickedPosit); + stream->Write(lastClickedPosit != NiPoint3Constant::ZERO); + if (lastClickedPosit != NiPoint3Constant::ZERO) stream->Write(lastClickedPosit); stream->Write(optionalOriginatorID); stream->Write(optionalTargetID != LWOOBJID_EMPTY); if (optionalTargetID != LWOOBJID_EMPTY) stream->Write(optionalTargetID); - stream->Write(originatorRot != NiQuaternion::IDENTITY); - if (originatorRot != NiQuaternion::IDENTITY) stream->Write(originatorRot); + stream->Write(originatorRot != NiQuaternionConstant::IDENTITY); + if (originatorRot != NiQuaternionConstant::IDENTITY) stream->Write(originatorRot); uint32_t sBitStreamLength = sBitStream.length(); stream->Write(sBitStreamLength); diff --git a/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp b/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp index f85e0561..a8edb14a 100644 --- a/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp +++ b/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp @@ -85,7 +85,7 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SetColGroup", 10, 0, 0, "", UNASSIGNED_SYSTEM_ADDRESS); //First rotate for anim - NiQuaternion rot = NiQuaternion::IDENTITY; + NiQuaternion rot = NiQuaternionConstant::IDENTITY; controllable->SetStatic(false); @@ -402,7 +402,7 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim const auto withdrawn = self->GetBoolean(u"isWithdrawn"); if (!withdrawn) return; - NiQuaternion rot = NiQuaternion::IDENTITY; + NiQuaternion rot = NiQuaternionConstant::IDENTITY; //First rotate for anim controllable->SetStatic(false); @@ -597,12 +597,12 @@ void BossSpiderQueenEnemyServer::OnUpdate(Entity* self) { if (!isWithdrawn) return; - if (controllable->GetRotation() == NiQuaternion::IDENTITY) { + if (controllable->GetRotation() == NiQuaternionConstant::IDENTITY) { return; } controllable->SetStatic(false); - controllable->SetRotation(NiQuaternion::IDENTITY); + controllable->SetRotation(NiQuaternionConstant::IDENTITY); controllable->SetStatic(true); Game::entityManager->SerializeEntity(self); diff --git a/dScripts/02_server/Map/AG/AgLaserSensorServer.cpp b/dScripts/02_server/Map/AG/AgLaserSensorServer.cpp index 7fcea9fa..6e19922a 100644 --- a/dScripts/02_server/Map/AG/AgLaserSensorServer.cpp +++ b/dScripts/02_server/Map/AG/AgLaserSensorServer.cpp @@ -13,7 +13,7 @@ void AgLaserSensorServer::OnStartup(Entity* self) { phantomPhysicsComponent->SetPhysicsEffectActive(true); phantomPhysicsComponent->SetEffectType(ePhysicsEffectType::REPULSE); phantomPhysicsComponent->SetDirectionalMultiplier(repelForce); - phantomPhysicsComponent->SetDirection(NiPoint3::UNIT_Y); + phantomPhysicsComponent->SetDirection(NiPoint3Constant::UNIT_Y); } diff --git a/dScripts/02_server/Map/AM/AmDrawBridge.cpp b/dScripts/02_server/Map/AM/AmDrawBridge.cpp index 11d52cd7..cd42f196 100644 --- a/dScripts/02_server/Map/AM/AmDrawBridge.cpp +++ b/dScripts/02_server/Map/AM/AmDrawBridge.cpp @@ -66,7 +66,7 @@ void AmDrawBridge::OnTimerDone(Entity* self, std::string timerName) { return; } - simplePhysicsComponent->SetAngularVelocity(NiPoint3::ZERO); + simplePhysicsComponent->SetAngularVelocity(NiPoint3Constant::ZERO); Game::entityManager->SerializeEntity(bridge); } diff --git a/dScripts/02_server/Map/GF/MastTeleport.cpp b/dScripts/02_server/Map/GF/MastTeleport.cpp index 5a40507d..e181779e 100644 --- a/dScripts/02_server/Map/GF/MastTeleport.cpp +++ b/dScripts/02_server/Map/GF/MastTeleport.cpp @@ -81,7 +81,7 @@ void MastTeleport::OnTimerDone(Entity* self, std::string timerName) { GameMessages::SendOrientToAngle(playerId, true, rads, player->GetSystemAddress()); - GameMessages::SendTeleport(playerId, position, NiQuaternion::IDENTITY, player->GetSystemAddress()); + GameMessages::SendTeleport(playerId, position, NiQuaternionConstant::IDENTITY, player->GetSystemAddress()); GameMessages::SendSetStunned(playerId, eStateChangeType::POP, player->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true diff --git a/dScripts/02_server/Pets/PetFromDigServer.cpp b/dScripts/02_server/Pets/PetFromDigServer.cpp index 525f3e94..33bab32a 100644 --- a/dScripts/02_server/Pets/PetFromDigServer.cpp +++ b/dScripts/02_server/Pets/PetFromDigServer.cpp @@ -40,6 +40,6 @@ void PetFromDigServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eP return; // TODO: Remove custom group? // Command the pet to the player as it may otherwise go to its spawn point which is non existant - // petComponent->Command(NiPoint3::ZERO, LWOOBJID_EMPTY, 6, 202, true); + // petComponent->Command(NiPoint3Constant::ZERO, LWOOBJID_EMPTY, 6, 202, true); } } diff --git a/dScripts/ai/GF/GfBanana.cpp b/dScripts/ai/GF/GfBanana.cpp index 6bc5c179..b06aae6f 100644 --- a/dScripts/ai/GF/GfBanana.cpp +++ b/dScripts/ai/GF/GfBanana.cpp @@ -56,7 +56,7 @@ void GfBanana::OnHit(Entity* self, Entity* attacker) { return; } - bananaEntity->SetPosition(bananaEntity->GetPosition() - NiPoint3::UNIT_Y * 8); + bananaEntity->SetPosition(bananaEntity->GetPosition() - NiPoint3Constant::UNIT_Y * 8); auto* bananaDestroyable = bananaEntity->GetComponent(); diff --git a/dScripts/client/ai/PR/CrabServer.cpp b/dScripts/client/ai/PR/CrabServer.cpp index f30142ba..6cdc2de8 100644 --- a/dScripts/client/ai/PR/CrabServer.cpp +++ b/dScripts/client/ai/PR/CrabServer.cpp @@ -39,6 +39,6 @@ void CrabServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, ePetTami return; // TODO: Remove custom group? // Command the pet to the player as it may otherwise go to its spawn point which is non existant - // petComponent->Command(NiPoint3::ZERO, LWOOBJID_EMPTY, 6, 202, true); + // petComponent->Command(NiPoint3Constant::ZERO, LWOOBJID_EMPTY, 6, 202, true); } } diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index d704bfea..6a8ed074 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -1031,8 +1031,8 @@ void HandlePacket(Packet* packet) { Game::entityManager->ConstructEntity(player, UNASSIGNED_SYSTEM_ADDRESS, true); - if (respawnPoint != NiPoint3::ZERO) { - GameMessages::SendPlayerReachedRespawnCheckpoint(player, respawnPoint, NiQuaternion::IDENTITY); + if (respawnPoint != NiPoint3Constant::ZERO) { + GameMessages::SendPlayerReachedRespawnCheckpoint(player, respawnPoint, NiQuaternionConstant::IDENTITY); } Game::entityManager->ConstructAllEntities(packet->systemAddress); diff --git a/dZoneManager/Spawner.h b/dZoneManager/Spawner.h index 79ba40d1..686c7588 100644 --- a/dZoneManager/Spawner.h +++ b/dZoneManager/Spawner.h @@ -12,8 +12,8 @@ #include "EntityInfo.h" struct SpawnerNode { - NiPoint3 position = NiPoint3::ZERO; - NiQuaternion rotation = NiQuaternion::IDENTITY; + NiPoint3 position = NiPoint3Constant::ZERO; + NiQuaternion rotation = NiQuaternionConstant::IDENTITY; uint32_t nodeID = 0; uint32_t nodeMax = 1; std::vector entities; diff --git a/tests/dCommonTests/TestNiPoint3.cpp b/tests/dCommonTests/TestNiPoint3.cpp index fbc98eb0..49814d15 100644 --- a/tests/dCommonTests/TestNiPoint3.cpp +++ b/tests/dCommonTests/TestNiPoint3.cpp @@ -8,9 +8,9 @@ */ TEST(dCommonTests, NiPoint3Test) { // Check that Unitize works - ASSERT_EQ(NiPoint3(3, 0, 0).Unitize(), NiPoint3::UNIT_X); + ASSERT_EQ(NiPoint3(3, 0, 0).Unitize(), NiPoint3Constant::UNIT_X); // Check what unitize does to a vector of length 0 - ASSERT_EQ(NiPoint3::ZERO.Unitize(), NiPoint3::ZERO); + ASSERT_EQ(NiPoint3Constant::ZERO.Unitize(), NiPoint3Constant::ZERO); } TEST(dCommonTests, NiPoint3OperatorTest) { diff --git a/tests/dGameTests/GameDependencies.h b/tests/dGameTests/GameDependencies.h index 8aefaa3d..11c320ba 100644 --- a/tests/dGameTests/GameDependencies.h +++ b/tests/dGameTests/GameDependencies.h @@ -25,8 +25,8 @@ public: class GameDependenciesTest : public ::testing::Test { protected: void SetUpDependencies() { - info.pos = NiPoint3::ZERO; - info.rot = NiQuaternion::IDENTITY; + info.pos = NiPoint3Constant::ZERO; + info.rot = NiQuaternionConstant::IDENTITY; info.scale = 1.0f; info.spawner = nullptr; info.lot = 999; From d78b50874c849e73628c2d1c18d0d9732a993abd Mon Sep 17 00:00:00 2001 From: jadebenn Date: Mon, 29 Jan 2024 21:45:50 -0600 Subject: [PATCH 04/50] chore: upgrade MacOS build settings for better C++20 compatibility (#1435) * upgrade MacOS build settings for better C++20 compatibility * add fixes I forgot * 3rd try * Update UserManager.cpp * Update CMakeLists.txt * End with newline * Update CMakeLists.txt * update to reflect feedback * Update CMakeLists.txt to disable deprecation warnings on SHA512 * attempt to disable sqlite warnings * revert last attempt (didn't work) * disable sqlite deprecation warnings on MacOS --- .github/workflows/build-and-test.yml | 10 ++++++---- CMakeLists.txt | 1 + CMakePresets.json | 10 +++++----- dCommon/CMakeLists.txt | 5 +++++ dGame/UserManager.cpp | 2 +- .../ControlBehaviorMessages/AddStripMessage.cpp | 4 ++++ .../ControlBehaviorMessages/AddStripMessage.h | 2 +- thirdparty/SQLite/CMakeLists.txt | 2 +- 8 files changed, 24 insertions(+), 12 deletions(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index ed7c0c7b..fc44885d 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -13,7 +13,7 @@ jobs: continue-on-error: true strategy: matrix: - os: [ windows-2022, ubuntu-22.04, macos-11 ] + os: [ windows-2022, ubuntu-22.04, macos-13 ] steps: - uses: actions/checkout@v3 @@ -25,9 +25,11 @@ jobs: with: vs-version: '[17,18)' msbuild-architecture: x64 - - name: Install libssl (Mac Only) - if: ${{ matrix.os == 'macos-11' }} - run: brew install openssl@3 + - name: Install libssl and switch to XCode 15.2 (Mac Only) + if: ${{ matrix.os == 'macos-13' }} + run: | + brew install openssl@3 + sudo xcode-select -s /Applications/Xcode_15.2.app/Contents/Developer - name: cmake uses: lukka/run-cmake@v10 with: diff --git a/CMakeLists.txt b/CMakeLists.txt index 09cbac97..1b6a775e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,6 +3,7 @@ project(Darkflame) include(CTest) set(CMAKE_CXX_STANDARD 20) +set(CXX_STANDARD_REQUIRED ON) set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake") # Read variables from file diff --git a/CMakePresets.json b/CMakePresets.json index 77b8b242..2feabc53 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -20,7 +20,7 @@ "inherits": "default" }, { - "name": "ci-macos-11", + "name": "ci-macos-13", "displayName": "CI configure step for MacOS", "description": "Same as default, Used in GitHub actions workflow", "inherits": "default" @@ -74,8 +74,8 @@ "jobs": 2 }, { - "name": "ci-macos-11", - "configurePreset": "ci-macos-11", + "name": "ci-macos-13", + "configurePreset": "ci-macos-13", "displayName": "MacOS CI Build", "description": "This preset is used by the CI build on MacOS", "jobs": 2 @@ -95,8 +95,8 @@ } }, { - "name": "ci-macos-11", - "configurePreset": "ci-macos-11", + "name": "ci-macos-13", + "configurePreset": "ci-macos-13", "displayName": "CI Tests on MacOS", "description": "Runs all tests on a Mac configuration", "execution": { diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt index fec1a2d7..32f24028 100644 --- a/dCommon/CMakeLists.txt +++ b/dCommon/CMakeLists.txt @@ -68,3 +68,8 @@ else () endif () target_link_libraries(dCommon ZLIB::ZLIB) + +# Disable deprecation warnings on MD5.cpp and SHA512.cpp for Apple Clang +if (APPLE) + set_source_files_properties("MD5.cpp" "SHA512.cpp" PROPERTIES COMPILE_FLAGS "-Wno-deprecated-declarations") +endif() diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index fc582108..b98569eb 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -451,7 +451,7 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) "User %i tried to rename a character that it does not own!", u->GetAccountID()); - std::find_if(u->GetCharacters().begin(), u->GetCharacters().end(), [&](Character* c) { + auto unusedItr = std::find_if(u->GetCharacters().begin(), u->GetCharacters().end(), [&](Character* c) { if (c->GetID() == charID) { character = c; return true; diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp index 5e75f6c4..6f0741dd 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp @@ -22,3 +22,7 @@ AddStripMessage::AddStripMessage(AMFArrayValue* arguments) : BehaviorMessageBase } LOG_DEBUG("number of actions %i", actionsToAdd.size()); } + +std::vector AddStripMessage::GetActionsToAdd() const { + return actionsToAdd; +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h index 0b9a09e3..5cceb510 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h @@ -21,7 +21,7 @@ public: AddStripMessage(AMFArrayValue* arguments); StripUiPosition GetPosition() const { return position; }; ActionContext GetActionContext() const { return actionContext; }; - std::vector GetActionsToAdd() const { return actionsToAdd; }; + std::vector GetActionsToAdd() const; private: StripUiPosition position; ActionContext actionContext; diff --git a/thirdparty/SQLite/CMakeLists.txt b/thirdparty/SQLite/CMakeLists.txt index ba45f015..3aa066a4 100644 --- a/thirdparty/SQLite/CMakeLists.txt +++ b/thirdparty/SQLite/CMakeLists.txt @@ -14,6 +14,6 @@ if(UNIX) if(NOT APPLE) target_compile_options(sqlite3 PRIVATE "-Wno-return-local-addr" "-Wno-maybe-uninitialized") else() - target_compile_options(sqlite3 PRIVATE "-Wno-return-stack-address" "-Wno-uninitialized") + target_compile_options(sqlite3 PRIVATE "-Wno-return-stack-address" "-Wno-uninitialized" "-Wno-deprecated-declarations") endif() endif() From b23981e59153fc00abd721694b74bd70c7b54405 Mon Sep 17 00:00:00 2001 From: jadebenn Date: Wed, 31 Jan 2024 08:38:38 -0600 Subject: [PATCH 05/50] chore: Update render component and delete unused code (#1429) * Update a few components to use smart pointers for memory management * 'final' keyword added to classes * removed duplicate 'const' * removed unused code * Updated render component to store effects directly in a vector * Use move instead of copy * make pointers const * attribute tags * nitpicking * delete default effect constructor * Added a vector size check to the RemoveEffect() function * use empty() instead of size() --- dGame/dComponents/CMakeLists.txt | 1 - dGame/dComponents/PropertyComponent.cpp | 11 --- dGame/dComponents/PropertyComponent.h | 18 +--- dGame/dComponents/RenderComponent.cpp | 115 +++++++----------------- dGame/dComponents/RenderComponent.h | 26 +++--- 5 files changed, 46 insertions(+), 125 deletions(-) delete mode 100644 dGame/dComponents/PropertyComponent.cpp diff --git a/dGame/dComponents/CMakeLists.txt b/dGame/dComponents/CMakeLists.txt index 59c49ce9..ac509e11 100644 --- a/dGame/dComponents/CMakeLists.txt +++ b/dGame/dComponents/CMakeLists.txt @@ -27,7 +27,6 @@ set(DGAME_DCOMPONENTS_SOURCES "PlayerForcedMovementComponent.cpp" "PossessableComponent.cpp" "PossessorComponent.cpp" - "PropertyComponent.cpp" "PropertyEntranceComponent.cpp" "PropertyManagementComponent.cpp" "PropertyVendorComponent.cpp" diff --git a/dGame/dComponents/PropertyComponent.cpp b/dGame/dComponents/PropertyComponent.cpp deleted file mode 100644 index 4f8df40c..00000000 --- a/dGame/dComponents/PropertyComponent.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include "PropertyComponent.h" -#include "GameMessages.h" -#include "dZoneManager.h" - -PropertyComponent::PropertyComponent(Entity* parent) : Component(parent) { - m_PropertyName = parent->GetVar(u"propertyName"); - m_PropertyState = new PropertyState(); -} - -PropertyComponent::~PropertyComponent() = default; - diff --git a/dGame/dComponents/PropertyComponent.h b/dGame/dComponents/PropertyComponent.h index c412ccb3..1085aac4 100644 --- a/dGame/dComponents/PropertyComponent.h +++ b/dGame/dComponents/PropertyComponent.h @@ -1,34 +1,22 @@ /* * Darkflame Universe - * Copyright 2018 + * Copyright 2024 */ #ifndef PROPERTYCOMPONENT_H #define PROPERTYCOMPONENT_H -#include "BitStream.h" #include "Entity.h" #include "Component.h" #include "eReplicaComponentType.h" -struct PropertyState { - LWOOBJID ownerID; - LWOOBJID propertyID; - bool rented; -}; - /** * This component is unused and has no functionality */ class PropertyComponent final : public Component { public: static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::PROPERTY; - explicit PropertyComponent(Entity* parentEntity); - ~PropertyComponent() override; - [[nodiscard]] PropertyState* GetPropertyState() const { return m_PropertyState; }; -private: - PropertyState* m_PropertyState; - std::string m_PropertyName; + explicit PropertyComponent(Entity* const parentEntity) noexcept : Component{ parentEntity } {} }; -#endif // PROPERTYCOMPONENT_H +#endif // !PROPERTYCOMPONENT_H diff --git a/dGame/dComponents/RenderComponent.cpp b/dGame/dComponents/RenderComponent.cpp index 4d8ff667..6616877f 100644 --- a/dGame/dComponents/RenderComponent.cpp +++ b/dGame/dComponents/RenderComponent.cpp @@ -1,7 +1,9 @@ #include "RenderComponent.h" +#include #include #include +#include #include #include "Entity.h" @@ -14,8 +16,7 @@ std::unordered_map RenderComponent::m_DurationCache{}; -RenderComponent::RenderComponent(Entity* parent, int32_t componentId): Component(parent) { - m_Effects = std::vector(); +RenderComponent::RenderComponent(Entity* const parentEntity, const int32_t componentId) : Component{ parentEntity } { m_LastAnimationName = ""; if (componentId == -1) return; @@ -42,100 +43,51 @@ RenderComponent::RenderComponent(Entity* parent, int32_t componentId): Component result.finalize(); } -RenderComponent::~RenderComponent() { - for (Effect* eff : m_Effects) { - if (eff) { - delete eff; - eff = nullptr; - } - } - - m_Effects.clear(); -} - void RenderComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { if (!bIsInitialUpdate) return; outBitStream->Write(m_Effects.size()); - for (Effect* eff : m_Effects) { - // we still need to write 0 as the size for name if it is a nullptr - if (!eff) { - outBitStream->Write(0); - continue; - } - - outBitStream->Write(eff->name.size()); + for (auto& eff : m_Effects) { + outBitStream->Write(eff.name.size()); // if there is no name, then we don't write anything else - if (eff->name.empty()) continue; + if (eff.name.empty()) continue; - for (const auto& value : eff->name) outBitStream->Write(value); + for (const auto& value : eff.name) outBitStream->Write(value); - outBitStream->Write(eff->effectID); + outBitStream->Write(eff.effectID); - outBitStream->Write(eff->type.size()); - for (const auto& value : eff->type) outBitStream->Write(value); + outBitStream->Write(eff.type.size()); + for (const auto& value : eff.type) outBitStream->Write(value); - outBitStream->Write(eff->priority); - outBitStream->Write(eff->secondary); + outBitStream->Write(eff.priority); + outBitStream->Write(eff.secondary); } } -Effect* RenderComponent::AddEffect(const int32_t effectId, const std::string& name, const std::u16string& type, const float priority) { - auto* eff = new Effect(); - - eff->effectID = effectId; - eff->name = name; - eff->type = type; - eff->priority = priority; - m_Effects.push_back(eff); - - return eff; +Effect& RenderComponent::AddEffect(const int32_t effectId, const std::string& name, const std::u16string& type, const float priority) { + return m_Effects.emplace_back(Effect{ effectId, name, type, priority }); } void RenderComponent::RemoveEffect(const std::string& name) { - uint32_t index = -1; + if (m_Effects.empty()) return; - for (auto i = 0u; i < m_Effects.size(); ++i) { - auto* eff = m_Effects[i]; + const auto effectToRemove = std::ranges::find_if(m_Effects, [&name](auto&& effect) { return effect.name == name; }); + if (effectToRemove == m_Effects.end()) return; // Return early if effect is not present - if (eff->name == name) { - index = i; - - delete eff; - - break; - } - } - - if (index == -1) { - return; - } - - m_Effects.erase(m_Effects.begin() + index); + const auto lastEffect = m_Effects.rbegin(); + *effectToRemove = std::move(*lastEffect); // Move-overwrite + m_Effects.pop_back(); } -void RenderComponent::Update(const float deltaTime) { - std::vector dead; +void RenderComponent::Update(const float deltaTime) { + for (auto& effect : m_Effects) { + if (effect.time == 0) continue; // Skip persistent effects - for (auto* effect : m_Effects) { - if (effect->time == 0) { - continue; // Skip persistent effects - } + const auto result = effect.time - deltaTime; + if (result <= 0) continue; - const auto result = effect->time - deltaTime; - - if (result <= 0) { - dead.push_back(effect); - - continue; - } - - effect->time = result; - } - - for (auto* effect : dead) { - // StopEffect(effect->name); + effect.time = result; } } @@ -144,12 +96,12 @@ void RenderComponent::PlayEffect(const int32_t effectId, const std::u16string& e GameMessages::SendPlayFXEffect(m_Parent, effectId, effectType, name, secondary, priority, scale, serialize); - auto* effect = AddEffect(effectId, name, effectType, priority); + auto& effect = AddEffect(effectId, name, effectType, priority); const auto& pair = m_DurationCache.find(effectId); if (pair != m_DurationCache.end()) { - effect->time = pair->second; + effect.time = pair->second; return; } @@ -168,16 +120,16 @@ void RenderComponent::PlayEffect(const int32_t effectId, const std::u16string& e m_DurationCache[effectId] = 0; - effect->time = 0; // Persistent effect + effect.time = 0; // Persistent effect return; } - effect->time = static_cast(result.getFloatField(0)); + effect.time = static_cast(result.getFloatField(0)); result.finalize(); - m_DurationCache[effectId] = effect->time; + m_DurationCache[effectId] = effect.time; } void RenderComponent::StopEffect(const std::string& name, const bool killImmediate) { @@ -186,11 +138,6 @@ void RenderComponent::StopEffect(const std::string& name, const bool killImmedia RemoveEffect(name); } -std::vector& RenderComponent::GetEffects() { - return m_Effects; -} - - float RenderComponent::PlayAnimation(Entity* self, const std::u16string& animation, float priority, float scale) { if (!self) return 0.0f; return RenderComponent::PlayAnimation(self, GeneralUtils::UTF16ToWTF8(animation), priority, scale); diff --git a/dGame/dComponents/RenderComponent.h b/dGame/dComponents/RenderComponent.h index 936864fc..87b210d7 100644 --- a/dGame/dComponents/RenderComponent.h +++ b/dGame/dComponents/RenderComponent.h @@ -17,7 +17,12 @@ class Entity; * here. */ struct Effect { - Effect() { priority = 1.0f; } + explicit Effect(const int32_t effectID, const std::string& name, const std::u16string& type, const float priority = 1.0f) noexcept + : effectID{ effectID } + , name{ name } + , type{ type } + , priority{ priority } { + } /** * The ID of the effect @@ -58,8 +63,7 @@ class RenderComponent final : public Component { public: static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::RENDER; - RenderComponent(Entity* entity, int32_t componentId = -1); - ~RenderComponent() override; + RenderComponent(Entity* const parentEntity, const int32_t componentId = -1); void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; void Update(float deltaTime) override; @@ -72,7 +76,7 @@ public: * @param priority the priority of the effect * @return if successful, the effect that was created */ - Effect* AddEffect(int32_t effectId, const std::string& name, const std::u16string& type, const float priority); + [[maybe_unused]] Effect& AddEffect(const int32_t effectId, const std::string& name, const std::u16string& type, const float priority); /** * Removes an effect for this entity @@ -99,12 +103,6 @@ public: */ void StopEffect(const std::string& name, bool killImmediate = true); - /** - * Returns the list of currently active effects - * @return - */ - std::vector& GetEffects(); - /** * Verifies that an animation can be played on this entity by checking * if it has the animation assigned to its group. If it does, the animation is echo'd @@ -125,10 +123,10 @@ public: static float PlayAnimation(Entity* self, const std::u16string& animation, float priority = 0.0f, float scale = 1.0f); static float PlayAnimation(Entity* self, const std::string& animation, float priority = 0.0f, float scale = 1.0f); - static float GetAnimationTime(Entity* self, const std::string& animation); - static float GetAnimationTime(Entity* self, const std::u16string& animation); + [[nodiscard]] static float GetAnimationTime(Entity* self, const std::string& animation); + [[nodiscard]] static float GetAnimationTime(Entity* self, const std::u16string& animation); - const std::string& GetLastAnimationName() const { return m_LastAnimationName; }; + [[nodiscard]] const std::string& GetLastAnimationName() const { return m_LastAnimationName; }; void SetLastAnimationName(const std::string& name) { m_LastAnimationName = name; }; private: @@ -136,7 +134,7 @@ private: /** * List of currently active effects */ - std::vector m_Effects; + std::vector m_Effects; std::vector m_animationGroupIds; From 050184c55860c10d818e8958e5426afc0eb735b4 Mon Sep 17 00:00:00 2001 From: jadebenn Date: Thu, 1 Feb 2024 09:43:28 -0600 Subject: [PATCH 06/50] chore: nitpicks on rendercomponent changes (#1440) * nitpicks on rendercomponent * undo constexpr --- dGame/dComponents/RenderComponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dGame/dComponents/RenderComponent.cpp b/dGame/dComponents/RenderComponent.cpp index 6616877f..449fbc4d 100644 --- a/dGame/dComponents/RenderComponent.cpp +++ b/dGame/dComponents/RenderComponent.cpp @@ -66,7 +66,7 @@ void RenderComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitial } Effect& RenderComponent::AddEffect(const int32_t effectId, const std::string& name, const std::u16string& type, const float priority) { - return m_Effects.emplace_back(Effect{ effectId, name, type, priority }); + return m_Effects.emplace_back(effectId, name, type, priority); } void RenderComponent::RemoveEffect(const std::string& name) { From f2e7d2eaacfa54ce4541dd270fb5a419cb4d9383 Mon Sep 17 00:00:00 2001 From: David Markowitz Date: Sun, 4 Feb 2024 06:10:07 -0800 Subject: [PATCH 07/50] Use vector instead of forward_list for dpGrid also swap contains in for find != end on an associative container since we are in c++20 now :) --- dPhysics/dpEntity.cpp | 2 +- dPhysics/dpGrid.cpp | 80 ++++++++++++++++++++----------------------- dPhysics/dpGrid.h | 10 +++--- 3 files changed, 44 insertions(+), 48 deletions(-) diff --git a/dPhysics/dpEntity.cpp b/dPhysics/dpEntity.cpp index 70bddb40..cbe3f5e8 100644 --- a/dPhysics/dpEntity.cpp +++ b/dPhysics/dpEntity.cpp @@ -76,7 +76,7 @@ void dpEntity::CheckCollision(dpEntity* other) { return; } - bool wasFound = (m_CurrentlyCollidingObjects.find(other->GetObjectID()) != m_CurrentlyCollidingObjects.end()); + bool wasFound = m_CurrentlyCollidingObjects.contains(other->GetObjectID()); bool isColliding = m_CollisionShape->IsColliding(other->GetShape()); diff --git a/dPhysics/dpGrid.cpp b/dPhysics/dpGrid.cpp index 1704e068..f498c491 100644 --- a/dPhysics/dpGrid.cpp +++ b/dPhysics/dpGrid.cpp @@ -8,24 +8,14 @@ dpGrid::dpGrid(int numCells, int cellSize) { CELL_SIZE = cellSize; m_DeleteGrid = true; - //fill x - for (int i = 0; i < NUM_CELLS; i++) { - m_Cells.push_back(std::vector>()); - } - - //fill z - for (int i = 0; i < NUM_CELLS; i++) { - for (int i = 0; i < NUM_CELLS; i++) { - m_Cells[i].push_back(std::forward_list()); - } - } + m_Cells.resize(NUM_CELLS, std::vector>(NUM_CELLS)); } dpGrid::~dpGrid() { if (!this->m_DeleteGrid) return; for (auto& x : m_Cells) { //x - for (auto& y : x) { //y - for (auto en : y) { + for (auto& z : x) { //y + for (auto en : z) { if (!en) continue; delete en; en = nullptr; @@ -39,13 +29,12 @@ void dpGrid::Add(dpEntity* entity) { int cellX = (int)std::round(entity->m_Position.x) / dpGrid::CELL_SIZE + NUM_CELLS / 2; int cellZ = (int)std::round(entity->m_Position.z) / dpGrid::CELL_SIZE + NUM_CELLS / 2; - if (cellX < 0) cellX = 0; - if (cellZ < 0) cellZ = 0; - if (cellX >= NUM_CELLS) cellX = NUM_CELLS - 1; - if (cellZ >= NUM_CELLS) cellZ = NUM_CELLS - 1; + // Clamp values to the range [0, NUM_CELLS - 1] + std::clamp(cellX, 0, NUM_CELLS - 1); + std::clamp(cellZ, 0, NUM_CELLS - 1); //Add to cell: - m_Cells[cellX][cellZ].push_front(entity); + m_Cells[cellX][cellZ].push_back(entity); //To verify that the object isn't gargantuan: if (entity->GetScale() >= CELL_SIZE * 2 || entity->GetIsGargantuan()) @@ -59,23 +48,27 @@ void dpGrid::Move(dpEntity* entity, float x, float z) { int cellX = (int)std::round(x) / dpGrid::CELL_SIZE + NUM_CELLS / 2; int cellZ = (int)std::round(z) / dpGrid::CELL_SIZE + NUM_CELLS / 2; - if (cellX < 0) cellX = 0; - if (cellZ < 0) cellZ = 0; - if (cellX >= NUM_CELLS) cellX = NUM_CELLS - 1; - if (cellZ >= NUM_CELLS) cellZ = NUM_CELLS - 1; + // Clamp values to the range [0, NUM_CELLS - 1] + std::clamp(cellX, 0, NUM_CELLS - 1); + std::clamp(cellZ, 0, NUM_CELLS - 1); - if (oldCellX < 0) oldCellX = 0; - if (oldCellZ < 0) oldCellZ = 0; - if (oldCellX >= NUM_CELLS) oldCellX = NUM_CELLS - 1; - if (oldCellZ >= NUM_CELLS) oldCellZ = NUM_CELLS - 1; + std::clamp(oldCellX, 0, NUM_CELLS - 1); + std::clamp(oldCellZ, 0, NUM_CELLS - 1); if (oldCellX == cellX && oldCellZ == cellZ) return; - //Remove from perv cell: - m_Cells[oldCellX][oldCellZ].remove(entity); + //Remove from prev cell: + auto& cell = m_Cells[oldCellX][oldCellZ]; + + // For speed, find the single match and swap it with the last element, then pop_back. + auto toRemove = std::find(cell.begin(), cell.end(), entity); + if (toRemove != cell.end()) { + *toRemove = cell.back(); + cell.pop_back(); + } //Add to the new cell - m_Cells[cellX][cellZ].push_front(entity); + m_Cells[cellX][cellZ].push_back(entity); } void dpGrid::Delete(dpEntity* entity) { @@ -83,15 +76,18 @@ void dpGrid::Delete(dpEntity* entity) { int oldCellX = (int)std::round(entity->m_Position.x) / dpGrid::CELL_SIZE + NUM_CELLS / 2; int oldCellZ = (int)std::round(entity->m_Position.z) / dpGrid::CELL_SIZE + NUM_CELLS / 2; - if (oldCellX < 0) oldCellX = 0; - if (oldCellZ < 0) oldCellZ = 0; - if (oldCellX >= NUM_CELLS) oldCellX = NUM_CELLS - 1; - if (oldCellZ >= NUM_CELLS) oldCellZ = NUM_CELLS - 1; + // Clamp values to the range [0, NUM_CELLS - 1] + std::clamp(oldCellX, 0, NUM_CELLS - 1); + std::clamp(oldCellZ, 0, NUM_CELLS - 1); - m_Cells[oldCellX][oldCellZ].remove(entity); + auto& cell = m_Cells[oldCellX][oldCellZ]; + auto toRemove = std::find(cell.begin(), cell.end(), entity); + if (toRemove != cell.end()) { + *toRemove = cell.back(); + cell.pop_back(); + } - if (m_GargantuanObjects.find(entity->m_ObjectID) != m_GargantuanObjects.end()) - m_GargantuanObjects.erase(entity->m_ObjectID); + m_GargantuanObjects.erase(entity->m_ObjectID); if (entity) delete entity; entity = nullptr; @@ -100,8 +96,8 @@ void dpGrid::Delete(dpEntity* entity) { void dpGrid::Update(float deltaTime) { //Pre-update: for (auto& x : m_Cells) { //x - for (auto& y : x) { //y - for (auto en : y) { + for (auto& z : x) { //y + for (auto en : z) { if (!en) continue; en->PreUpdate(); } @@ -110,8 +106,8 @@ void dpGrid::Update(float deltaTime) { //Actual collision detection update: for (int x = 0; x < NUM_CELLS; x++) { - for (int y = 0; y < NUM_CELLS; y++) { - HandleCell(x, y, deltaTime); + for (int z = 0; z < NUM_CELLS; z++) { + HandleCell(x, z, deltaTime); } } } @@ -157,7 +153,7 @@ void dpGrid::HandleCell(int x, int z, float deltaTime) { HandleEntity(en, other); } - for (auto other : m_GargantuanObjects) - HandleEntity(en, other.second); + for (auto& [id, entity] : m_GargantuanObjects) + HandleEntity(en, entity); } } diff --git a/dPhysics/dpGrid.h b/dPhysics/dpGrid.h index 229e7449..39a9cfe7 100644 --- a/dPhysics/dpGrid.h +++ b/dPhysics/dpGrid.h @@ -1,8 +1,7 @@ #pragma once -#include -#include -#include #include +#include + #include "dCommonVars.h" class dpEntity; @@ -30,7 +29,8 @@ public: */ void SetDeleteGrid(bool value) { this->m_DeleteGrid = value; }; - std::vector>> GetCells() { return this->m_Cells; }; + // Intentional copy since this is only used when we delete this class to re-create it. + std::vector>> GetCells() { return this->m_Cells; }; private: void HandleEntity(dpEntity* entity, dpEntity* other); @@ -38,7 +38,7 @@ private: private: //cells on X, cells on Y for that X, then another vector that contains the entities within that cell. - std::vector>> m_Cells; + std::vector>> m_Cells; std::map m_GargantuanObjects; bool m_DeleteGrid = true; }; From f0b6ad89d99fc7d502fc1f8845750ca4a009e8fc Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 4 Feb 2024 06:29:05 -0800 Subject: [PATCH 08/50] chore: Player class removal (#1445) * SystemAddress and destructor * move respawn logic to character comp Tested that respawn pos and rot can be set as per previously by crossing a respawn point and smashing to see if I would respawn at the new place. * Move loot cheat checking * Remove GetParentUser overload Tested completing missions control behaviors collecting life crate completing a bunch of missions using macros loading into worlds brick-by-brick placing models digging the x spot in gnarled forest can still ban and mute players cheat detection is still doing its thing flags are still set (checked with flag 45) claim codes still work (created new char, checked the lego club mail was there) * Move player constructor logic Its now at the bottom of Entity constructor. Time to remove Player * Remove Player class Removes the Player class. Tested that I can still login and see another player in Venture Explorer and logging out a few times still works as well as smashing enemies * store ptr * Update SlashCommandHandler.cpp --- dGame/CMakeLists.txt | 1 - dGame/Character.h | 2 + dGame/Entity.cpp | 118 +++++++++++++----- dGame/Entity.h | 20 ++- dGame/EntityManager.cpp | 12 +- dGame/EntityManager.h | 2 +- dGame/Player.cpp | 71 ----------- dGame/Player.h | 62 --------- dGame/PlayerManager.cpp | 23 ++-- dGame/PlayerManager.h | 14 +-- dGame/dComponents/ActivityComponent.cpp | 1 - dGame/dComponents/CharacterComponent.cpp | 24 +++- dGame/dComponents/CharacterComponent.h | 29 ++++- dGame/dComponents/DestroyableComponent.cpp | 15 ++- dGame/dComponents/InventoryComponent.cpp | 1 - .../PropertyManagementComponent.cpp | 3 - dGame/dComponents/RacingControlComponent.cpp | 1 - dGame/dComponents/TriggerComponent.cpp | 1 - dGame/dGameMessages/GameMessageHandler.cpp | 1 - dGame/dGameMessages/GameMessages.cpp | 13 +- dGame/dMission/Mission.cpp | 13 +- dGame/dMission/Mission.h | 3 +- dGame/dPropertyBehaviors/ControlBehaviors.cpp | 5 +- dGame/dUtilities/CheatDetection.cpp | 5 +- dGame/dUtilities/SlashCommandHandler.cpp | 15 ++- .../02_server/Map/General/PetDigServer.cpp | 2 +- .../ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp | 1 - dWorldServer/WorldServer.cpp | 17 +-- 28 files changed, 215 insertions(+), 260 deletions(-) delete mode 100644 dGame/Player.cpp delete mode 100644 dGame/Player.h diff --git a/dGame/CMakeLists.txt b/dGame/CMakeLists.txt index 4d9a3e50..627f163a 100644 --- a/dGame/CMakeLists.txt +++ b/dGame/CMakeLists.txt @@ -2,7 +2,6 @@ set(DGAME_SOURCES "Character.cpp" "Entity.cpp" "EntityManager.cpp" "LeaderboardManager.cpp" - "Player.cpp" "PlayerManager.cpp" "TeamManager.cpp" "TradingManager.cpp" diff --git a/dGame/Character.h b/dGame/Character.h index 6c8ead30..b994fb61 100644 --- a/dGame/Character.h +++ b/dGame/Character.h @@ -457,6 +457,8 @@ public: void SetBillboardVisible(bool visible); + User* GetParentUser() const { return m_ParentUser; } + private: void UpdateInfoFromDatabase(); /** diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 89b925c6..50ef5df2 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -15,7 +15,6 @@ #include "Spawner.h" #include "UserManager.h" #include "dpWorld.h" -#include "Player.h" #include "LUTriggers.h" #include "User.h" #include "EntityTimer.h" @@ -26,6 +25,7 @@ #include "eObjectBits.h" #include "PositionUpdate.h" #include "eChatMessageType.h" +#include "PlayerManager.h" //Component includes: #include "Component.h" @@ -95,7 +95,7 @@ #include "CDSkillBehaviorTable.h" #include "CDZoneTableTable.h" -Entity::Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity) { +Entity::Entity(const LWOOBJID& objectID, EntityInfo info, User* parentUser, Entity* parentEntity) { m_ObjectID = objectID; m_TemplateID = info.lot; m_ParentEntity = parentEntity; @@ -124,9 +124,42 @@ Entity::Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity) m_SpawnerNodeID = info.spawnerNodeID; if (info.lot != 1) m_PlayerIsReadyForUpdates = true; + if (parentUser) { + m_Character = parentUser->GetLastUsedChar(); + parentUser->SetLoggedInChar(objectID); + m_GMLevel = m_Character->GetGMLevel(); + + m_Character->SetEntity(this); + + PlayerManager::AddPlayer(this); + } } Entity::~Entity() { + if (IsPlayer()) { + LOG("Deleted player"); + + // Make sure the player exists first. Remove afterwards to prevent the OnPlayerExist functions from not being able to find the player. + if (!PlayerManager::RemovePlayer(this)) { + LOG("Unable to find player to remove from manager."); + return; + } + + Entity* zoneControl = Game::entityManager->GetZoneControlEntity(); + for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { + script->OnPlayerExit(zoneControl, this); + } + + std::vector scriptedActs = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY); + for (Entity* scriptEntity : scriptedActs) { + if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds + for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { + script->OnPlayerExit(scriptEntity, this); + } + } + } + } + if (m_Character) { m_Character->SaveXMLToDatabase(); } @@ -212,7 +245,7 @@ void Entity::Initialize() { * Not all components are implemented. Some are represented by a nullptr, as they hold no data. */ - if (GetParentUser()) { + if (m_Character && m_Character->GetParentUser()) { AddComponent()->LoadFromXml(m_Character->GetXMLDoc()); } @@ -437,7 +470,8 @@ void Entity::Initialize() { AddComponent(); - AddComponent(m_Character)->LoadFromXml(m_Character->GetXMLDoc()); + auto& systemAddress = m_Character->GetParentUser() ? m_Character->GetParentUser()->GetSystemAddress() : UNASSIGNED_SYSTEM_ADDRESS; + AddComponent(m_Character, systemAddress)->LoadFromXml(m_Character->GetXMLDoc()); AddComponent(); } @@ -788,14 +822,6 @@ bool Entity::operator!=(const Entity& other) const { return other.m_ObjectID != m_ObjectID; } -User* Entity::GetParentUser() const { - if (!IsPlayer()) { - return nullptr; - } - - return static_cast(this)->GetParentUser(); -} - Component* Entity::GetComponent(eReplicaComponentType componentID) const { const auto& index = m_Components.find(componentID); @@ -850,17 +876,12 @@ void Entity::SetProximityRadius(dpEntity* entity, std::string name) { void Entity::SetGMLevel(eGameMasterLevel value) { m_GMLevel = value; - if (GetParentUser()) { - Character* character = GetParentUser()->GetLastUsedChar(); + if (m_Character) m_Character->SetGMLevel(value); - if (character) { - character->SetGMLevel(value); - } - } + auto* characterComponent = GetComponent(); + if (!characterComponent) return; - CharacterComponent* character = GetComponent(); - if (!character) return; - character->SetGMLevel(value); + characterComponent->SetGMLevel(value); GameMessages::SendGMLevelBroadcast(m_ObjectID, value); @@ -1630,18 +1651,23 @@ bool Entity::GetIsDead() const { void Entity::AddLootItem(const Loot::Info& info) { if (!IsPlayer()) return; - auto& droppedLoot = static_cast(this)->GetDroppedLoot(); + + auto* characterComponent = GetComponent(); + if (!characterComponent) return; + + auto& droppedLoot = characterComponent->GetDroppedLoot(); droppedLoot.insert(std::make_pair(info.id, info)); } void Entity::PickupItem(const LWOOBJID& objectID) { if (!IsPlayer()) return; InventoryComponent* inv = GetComponent(); - if (!inv) return; + auto* characterComponent = GetComponent(); + if (!inv || !characterComponent) return; CDObjectsTable* objectsTable = CDClientManager::Instance().GetTable(); - auto& droppedLoot = static_cast(this)->GetDroppedLoot(); + auto& droppedLoot = characterComponent->GetDroppedLoot(); for (const auto& p : droppedLoot) { if (p.first == objectID) { @@ -1677,22 +1703,28 @@ void Entity::PickupItem(const LWOOBJID& objectID) { bool Entity::CanPickupCoins(uint64_t count) { if (!IsPlayer()) return false; - auto* player = static_cast(this); - auto droppedCoins = player->GetDroppedCoins(); + + auto* characterComponent = GetComponent(); + if (!characterComponent) return false; + + auto droppedCoins = characterComponent->GetDroppedCoins(); if (count > droppedCoins) { return false; } else { - player->SetDroppedCoins(droppedCoins - count); + characterComponent->SetDroppedCoins(droppedCoins - count); return true; } } void Entity::RegisterCoinDrop(uint64_t count) { if (!IsPlayer()) return; - auto* player = static_cast(this); - auto droppedCoins = player->GetDroppedCoins(); + + auto* characterComponent = GetComponent(); + if (!characterComponent) return; + + auto droppedCoins = characterComponent->GetDroppedCoins(); droppedCoins += count; - player->SetDroppedCoins(droppedCoins); + characterComponent->SetDroppedCoins(droppedCoins); } void Entity::AddChild(Entity* child) { @@ -1990,7 +2022,7 @@ std::vector Entity::GetTargetsInPhantom() { // Clean up invalid targets, like disconnected players m_TargetsInPhantom.erase(std::remove_if(m_TargetsInPhantom.begin(), m_TargetsInPhantom.end(), [](const LWOOBJID id) { return !Game::entityManager->GetEntity(id); - }), m_TargetsInPhantom.end()); + }), m_TargetsInPhantom.end()); std::vector enemies; for (const auto id : m_TargetsInPhantom) { @@ -2133,3 +2165,27 @@ void Entity::ProcessPositionUpdate(PositionUpdate& update) { if (updateChar) Game::entityManager->SerializeEntity(this); } + +const SystemAddress& Entity::GetSystemAddress() const { + auto* characterComponent = GetComponent(); + return characterComponent ? characterComponent->GetSystemAddress() : UNASSIGNED_SYSTEM_ADDRESS; +} + +const NiPoint3& Entity::GetRespawnPosition() const { + auto* characterComponent = GetComponent(); + return characterComponent ? characterComponent->GetRespawnPosition() : NiPoint3Constant::ZERO; +} + +const NiQuaternion& Entity::GetRespawnRotation() const { + auto* characterComponent = GetComponent(); + return characterComponent ? characterComponent->GetRespawnRotation() : NiQuaternionConstant::IDENTITY; +} + +void Entity::SetRespawnPos(const NiPoint3& position) { + auto* characterComponent = GetComponent(); + if (characterComponent) characterComponent->SetRespawnPos(position); +} +void Entity::SetRespawnRot(const NiQuaternion& rotation) { + auto* characterComponent = GetComponent(); + if (characterComponent) characterComponent->SetRespawnRot(rotation); +} diff --git a/dGame/Entity.h b/dGame/Entity.h index 3074842a..eb6eb956 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -47,10 +47,10 @@ namespace CppScripts { */ class Entity { public: - explicit Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity = nullptr); - virtual ~Entity(); + explicit Entity(const LWOOBJID& objectID, EntityInfo info, User* parentUser = nullptr, Entity* parentEntity = nullptr); + ~Entity(); - virtual void Initialize(); + void Initialize(); bool operator==(const Entity& other) const; bool operator!=(const Entity& other) const; @@ -104,9 +104,7 @@ public: const NiQuaternion& GetRotation() const; - virtual User* GetParentUser() const; - - virtual const SystemAddress& GetSystemAddress() const { return UNASSIGNED_SYSTEM_ADDRESS; }; + const SystemAddress& GetSystemAddress() const; /** * Setters @@ -128,11 +126,9 @@ public: void SetRotation(const NiQuaternion& rotation); - virtual void SetRespawnPos(const NiPoint3& position) {} + void SetRespawnPos(const NiPoint3& position); - virtual void SetRespawnRot(const NiQuaternion& rotation) {} - - virtual void SetSystemAddress(const SystemAddress& value) {}; + void SetRespawnRot(const NiQuaternion& rotation); /** * Component management @@ -229,8 +225,8 @@ public: void TriggerEvent(eTriggerEventType event, Entity* optionalTarget = nullptr); void ScheduleDestructionAfterUpdate() { m_ShouldDestroyAfterUpdate = true; } - virtual const NiPoint3& GetRespawnPosition() const { return NiPoint3Constant::ZERO; } - virtual const NiQuaternion& GetRespawnRotation() const { return NiQuaternionConstant::IDENTITY; } + const NiPoint3& GetRespawnPosition() const; + const NiQuaternion& GetRespawnRotation() const; void Sleep(); void Wake(); diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index 10655d25..e1f2f46e 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -7,7 +7,6 @@ #include "GeneralUtils.h" #include "dServer.h" #include "Spawner.h" -#include "Player.h" #include "SkillComponent.h" #include "SwitchComponent.h" #include "UserManager.h" @@ -118,14 +117,7 @@ Entity* EntityManager::CreateEntity(EntityInfo info, User* user, Entity* parentE info.id = id; - Entity* entity; - - // Check if the entitty if a player, in case use the extended player entity class - if (user != nullptr) { - entity = new Player(id, info, user, parentEntity); - } else { - entity = new Entity(id, info, parentEntity); - } + Entity* entity = new Entity(id, info, user, parentEntity); // Initialize the entity entity->Initialize(); @@ -482,7 +474,7 @@ void EntityManager::UpdateGhosting() { m_PlayersToUpdateGhosting.clear(); } -void EntityManager::UpdateGhosting(Player* player) { +void EntityManager::UpdateGhosting(Entity* player) { if (player == nullptr) { return; } diff --git a/dGame/EntityManager.h b/dGame/EntityManager.h index 33d7aaff..352b927b 100644 --- a/dGame/EntityManager.h +++ b/dGame/EntityManager.h @@ -55,7 +55,7 @@ public: float GetGhostDistanceMin() const; void QueueGhostUpdate(LWOOBJID playerID); void UpdateGhosting(); - void UpdateGhosting(Player* player); + void UpdateGhosting(Entity* player); void CheckGhosting(Entity* entity); Entity* GetGhostCandidate(int32_t id); bool GetGhostingEnabled() const; diff --git a/dGame/Player.cpp b/dGame/Player.cpp deleted file mode 100644 index 8f414b43..00000000 --- a/dGame/Player.cpp +++ /dev/null @@ -1,71 +0,0 @@ -#include "Player.h" - -#include - -#include "Character.h" -#include "UserManager.h" -#include "EntityManager.h" -#include "Game.h" -#include "Logger.h" -#include "dZoneManager.h" -#include "User.h" -#include "CppScripts.h" -#include "Loot.h" -#include "eReplicaComponentType.h" -#include "PlayerManager.h" - -void Player::SetRespawnPos(const NiPoint3& position) { - if (!m_Character) return; - - m_respawnPos = position; - - m_Character->SetRespawnPoint(Game::zoneManager->GetZone()->GetWorldID(), position); - -} - -void Player::SetRespawnRot(const NiQuaternion& rotation) { - m_respawnRot = rotation; -} - -void Player::SetSystemAddress(const SystemAddress& value) { - m_SystemAddress = value; -} - -Player::Player(const LWOOBJID& objectID, const EntityInfo info, User* user, Entity* parentEntity) : Entity(objectID, info, parentEntity) { - m_ParentUser = user; - m_Character = m_ParentUser->GetLastUsedChar(); - m_ParentUser->SetLoggedInChar(objectID); - m_GMLevel = m_Character->GetGMLevel(); - m_SystemAddress = m_ParentUser->GetSystemAddress(); - m_DroppedCoins = 0; - - m_Character->SetEntity(this); - - PlayerManager::AddPlayer(this); -} - -Player::~Player() { - LOG("Deleted player"); - - // Make sure the player exists first. Remove afterwards to prevent the OnPlayerExist functions from not being able to find the player. - if (!PlayerManager::RemovePlayer(this)) { - LOG("Unable to find player to remove from manager."); - return; - } - - if (IsPlayer()) { - Entity* zoneControl = Game::entityManager->GetZoneControlEntity(); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { - script->OnPlayerExit(zoneControl, this); - } - - std::vector scriptedActs = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY); - for (Entity* scriptEntity : scriptedActs) { - if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds - for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { - script->OnPlayerExit(scriptEntity, this); - } - } - } - } -} diff --git a/dGame/Player.h b/dGame/Player.h deleted file mode 100644 index dd8efd9c..00000000 --- a/dGame/Player.h +++ /dev/null @@ -1,62 +0,0 @@ -#pragma once - -#include "Entity.h" - -/** - * Extended Entity for player data and behavior. - * - * Contains properties only a player entity would require, like associated SystemAddress and User. - * - * Keeps track of which entities are observed by this user for ghosting. - */ -class Player final : public Entity -{ -public: - explicit Player(const LWOOBJID& objectID, EntityInfo info, User* user, Entity* parentEntity = nullptr); - - /** - * Getters - */ - - User* GetParentUser() const override { return m_ParentUser; }; - - const SystemAddress& GetSystemAddress() const override { return m_SystemAddress; }; - - const NiPoint3& GetRespawnPosition() const override { return m_respawnPos; }; - - const NiQuaternion& GetRespawnRotation() const override { return m_respawnRot; }; - - std::map& GetDroppedLoot() { return m_DroppedLoot; }; - - uint64_t GetDroppedCoins() const { return m_DroppedCoins; }; - - /** - * Setters - */ - - void SetDroppedCoins(const uint64_t value) { m_DroppedCoins = value; }; - - void SetSystemAddress(const SystemAddress& value) override; - - void SetRespawnPos(const NiPoint3& position) override; - - void SetRespawnRot(const NiQuaternion& rotation) override; - - /** - * Ghosting - */ - - ~Player() override; -private: - SystemAddress m_SystemAddress; - - NiPoint3 m_respawnPos; - - NiQuaternion m_respawnRot; - - User* m_ParentUser; - - std::map m_DroppedLoot; - - uint64_t m_DroppedCoins; -}; diff --git a/dGame/PlayerManager.cpp b/dGame/PlayerManager.cpp index e3017f05..61e2568d 100644 --- a/dGame/PlayerManager.cpp +++ b/dGame/PlayerManager.cpp @@ -1,20 +1,19 @@ #include "PlayerManager.h" #include "Character.h" -#include "Player.h" #include "User.h" #include "UserManager.h" #include "eReplicaComponentType.h" namespace { - std::vector m_Players; + std::vector m_Players; }; -const std::vector& PlayerManager::GetAllPlayers() { +const std::vector& PlayerManager::GetAllPlayers() { return m_Players; } -void PlayerManager::AddPlayer(Player* player) { +void PlayerManager::AddPlayer(Entity* player) { const auto& iter = std::find(m_Players.begin(), m_Players.end(), player); if (iter == m_Players.end()) { @@ -22,7 +21,7 @@ void PlayerManager::AddPlayer(Player* player) { } } -bool PlayerManager::RemovePlayer(Player* player) { +bool PlayerManager::RemovePlayer(Entity* player) { const auto iter = std::find(m_Players.begin(), m_Players.end(), player); const bool toReturn = iter != m_Players.end(); @@ -33,21 +32,21 @@ bool PlayerManager::RemovePlayer(Player* player) { return toReturn; } -Player* PlayerManager::GetPlayer(const SystemAddress& sysAddr) { +Entity* PlayerManager::GetPlayer(const SystemAddress& sysAddr) { auto* entity = UserManager::Instance()->GetUser(sysAddr)->GetLastUsedChar()->GetEntity(); - return static_cast(entity); + return entity; } -Player* PlayerManager::GetPlayer(const std::string& name) { +Entity* PlayerManager::GetPlayer(const std::string& name) { const auto characters = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::CHARACTER); - Player* player = nullptr; + Entity* player = nullptr; for (auto* character : characters) { if (!character->IsPlayer()) continue; if (GeneralUtils::CaseInsensitiveStringCompare(name, character->GetCharacter()->GetName())) { - player = dynamic_cast(character); + player = character; break; } } @@ -55,8 +54,8 @@ Player* PlayerManager::GetPlayer(const std::string& name) { return player; } -Player* PlayerManager::GetPlayer(LWOOBJID playerID) { - Player* playerToReturn = nullptr; +Entity* PlayerManager::GetPlayer(LWOOBJID playerID) { + Entity* playerToReturn = nullptr; for (auto* player : m_Players) { if (player->GetObjectID() == playerID) { playerToReturn = player; diff --git a/dGame/PlayerManager.h b/dGame/PlayerManager.h index bb54f83b..7f6be5ba 100644 --- a/dGame/PlayerManager.h +++ b/dGame/PlayerManager.h @@ -5,21 +5,21 @@ #include -class Player; +class Entity; struct SystemAddress; namespace PlayerManager { - void AddPlayer(Player* player); + void AddPlayer(Entity* player); - bool RemovePlayer(Player* player); + bool RemovePlayer(Entity* player); - Player* GetPlayer(const SystemAddress& sysAddr); + Entity* GetPlayer(const SystemAddress& sysAddr); - Player* GetPlayer(const std::string& name); + Entity* GetPlayer(const std::string& name); - Player* GetPlayer(LWOOBJID playerID); + Entity* GetPlayer(LWOOBJID playerID); - const std::vector& GetAllPlayers(); + const std::vector& GetAllPlayers(); }; #endif //!__PLAYERMANAGER__H__ diff --git a/dGame/dComponents/ActivityComponent.cpp b/dGame/dComponents/ActivityComponent.cpp index aa6a4604..60a95952 100644 --- a/dGame/dComponents/ActivityComponent.cpp +++ b/dGame/dComponents/ActivityComponent.cpp @@ -10,7 +10,6 @@ #include "WorldPackets.h" #include "EntityManager.h" #include "ChatPackets.h" -#include "Player.h" #include "BitStreamUtils.h" #include "dServer.h" #include "GeneralUtils.h" diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index 70eec0cf..61b744f1 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -24,7 +24,7 @@ #include "WorldPackets.h" #include -CharacterComponent::CharacterComponent(Entity* parent, Character* character) : Component(parent) { +CharacterComponent::CharacterComponent(Entity* parent, Character* character, const SystemAddress& systemAddress) : Component(parent) { m_Character = character; m_IsRacing = false; @@ -46,6 +46,7 @@ CharacterComponent::CharacterComponent(Entity* parent, Character* character) : C m_CurrentActivity = eGameActivity::NONE; m_CountryCode = 0; m_LastUpdateTimestamp = std::time(nullptr); + m_SystemAddress = systemAddress; } bool CharacterComponent::LandingAnimDisabled(int zoneID) { @@ -762,8 +763,8 @@ void CharacterComponent::UpdateClientMinimap(bool showFaction, std::string ventu } void CharacterComponent::AwardClaimCodes() { - if (!m_Parent) return; - auto* user = m_Parent->GetParentUser(); + if (!m_Parent || !m_Parent->GetCharacter()) return; + auto* user = m_Parent->GetCharacter()->GetParentUser(); if (!user) return; auto rewardCodes = Database::Get()->GetRewardCodesByAccountID(user->GetAccountID()); @@ -817,3 +818,20 @@ void CharacterComponent::SendToZone(LWOMAPID zoneId, LWOCLONEID cloneId) const { Game::entityManager->DestructEntity(entity); }); } + +const SystemAddress& CharacterComponent::GetSystemAddress() const { + return m_SystemAddress; +} + +void CharacterComponent::SetRespawnPos(const NiPoint3& position) { + if (!m_Character) return; + + m_respawnPos = position; + + m_Character->SetRespawnPoint(Game::zoneManager->GetZone()->GetWorldID(), position); + +} + +void CharacterComponent::SetRespawnRot(const NiQuaternion& rotation) { + m_respawnRot = rotation; +} diff --git a/dGame/dComponents/CharacterComponent.h b/dGame/dComponents/CharacterComponent.h index a44d359d..01c26f9a 100644 --- a/dGame/dComponents/CharacterComponent.h +++ b/dGame/dComponents/CharacterComponent.h @@ -11,6 +11,7 @@ #include "tinyxml2.h" #include "eReplicaComponentType.h" #include +#include "Loot.h" enum class eGameActivity : uint32_t; @@ -65,7 +66,7 @@ class CharacterComponent final : public Component { public: static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::CHARACTER; - CharacterComponent(Entity* parent, Character* character); + CharacterComponent(Entity* parent, Character* character, const SystemAddress& systemAddress); ~CharacterComponent() override; void LoadFromXml(tinyxml2::XMLDocument* doc) override; @@ -289,6 +290,22 @@ public: */ void SendToZone(LWOMAPID zoneId, LWOCLONEID cloneId = 0) const; + const SystemAddress& GetSystemAddress() const; + + const NiPoint3& GetRespawnPosition() const { return m_respawnPos; }; + + void SetRespawnPos(const NiPoint3& position); + + const NiQuaternion& GetRespawnRotation() const { return m_respawnRot; }; + + void SetRespawnRot(const NiQuaternion& rotation); + + std::map& GetDroppedLoot() { return m_DroppedLoot; }; + + uint64_t GetDroppedCoins() const { return m_DroppedCoins; }; + + void SetDroppedCoins(const uint64_t value) { m_DroppedCoins = value; }; + /** * Character info regarding this character, including clothing styles, etc. */ @@ -579,6 +596,16 @@ private: std::array m_ClaimCodes{}; void AwardClaimCodes(); + + SystemAddress m_SystemAddress; + + NiPoint3 m_respawnPos; + + NiQuaternion m_respawnRot; + + std::map m_DroppedLoot; + + uint64_t m_DroppedCoins = 0; }; #endif // CHARACTERCOMPONENT_H diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 64dca4f1..fd89da4d 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -251,13 +251,14 @@ void DestroyableComponent::SetMaxHealth(float value, bool playAnim) { if (playAnim) { // Now update the player bar - if (!m_Parent->GetParentUser()) return; + auto* characterComponent = m_Parent->GetComponent(); + if (!characterComponent) return; AMFArrayValue args; args.Insert("amount", std::to_string(difference)); args.Insert("type", "health"); - GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", args); + GameMessages::SendUIMessageServerToSingleClient(m_Parent, characterComponent->GetSystemAddress(), "MaxPlayerBarUpdate", args); } Game::entityManager->SerializeEntity(m_Parent); @@ -292,13 +293,14 @@ void DestroyableComponent::SetMaxArmor(float value, bool playAnim) { if (playAnim) { // Now update the player bar - if (!m_Parent->GetParentUser()) return; + auto* characterComponent = m_Parent->GetComponent(); + if (!characterComponent) return; AMFArrayValue args; args.Insert("amount", std::to_string(value)); args.Insert("type", "armor"); - GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", args); + GameMessages::SendUIMessageServerToSingleClient(m_Parent, characterComponent->GetSystemAddress(), "MaxPlayerBarUpdate", args); } Game::entityManager->SerializeEntity(m_Parent); @@ -332,13 +334,14 @@ void DestroyableComponent::SetMaxImagination(float value, bool playAnim) { if (playAnim) { // Now update the player bar - if (!m_Parent->GetParentUser()) return; + auto* characterComponent = m_Parent->GetComponent(); + if (!characterComponent) return; AMFArrayValue args; args.Insert("amount", std::to_string(difference)); args.Insert("type", "imagination"); - GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", args); + GameMessages::SendUIMessageServerToSingleClient(m_Parent, characterComponent->GetSystemAddress(), "MaxPlayerBarUpdate", args); } Game::entityManager->SerializeEntity(m_Parent); } diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 5e6af885..97c1198b 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -14,7 +14,6 @@ #include "Character.h" #include "EntityManager.h" #include "ItemSet.h" -#include "Player.h" #include "PetComponent.h" #include "PossessorComponent.h" #include "PossessableComponent.h" diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index 0f6eb5a8..0dfc04af 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -14,7 +14,6 @@ #include "Item.h" #include "Database.h" #include "ObjectIDManager.h" -#include "Player.h" #include "RocketLaunchpadControlComponent.h" #include "PropertyEntranceComponent.h" #include "InventoryComponent.h" @@ -177,8 +176,6 @@ bool PropertyManagementComponent::Claim(const LWOOBJID playerId) { auto* entity = Game::entityManager->GetEntity(playerId); - auto* user = entity->GetParentUser(); - auto character = entity->GetCharacter(); if (!character) return false; diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index 742563cc..824e7f36 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -12,7 +12,6 @@ #include "Item.h" #include "MissionComponent.h" #include "ModuleAssemblyComponent.h" -#include "Player.h" #include "PossessableComponent.h" #include "PossessorComponent.h" #include "eRacingTaskParam.h" diff --git a/dGame/dComponents/TriggerComponent.cpp b/dGame/dComponents/TriggerComponent.cpp index 6b83ae73..bb297dbc 100644 --- a/dGame/dComponents/TriggerComponent.cpp +++ b/dGame/dComponents/TriggerComponent.cpp @@ -9,7 +9,6 @@ #include "ControllablePhysicsComponent.h" #include "MissionComponent.h" #include "PhantomPhysicsComponent.h" -#include "Player.h" #include "QuickBuildComponent.h" #include "SkillComponent.h" #include "eEndBehavior.h" diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index fa11c086..07df3c60 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -18,7 +18,6 @@ #include "Character.h" #include "ControllablePhysicsComponent.h" #include "dZoneManager.h" -#include "Player.h" #include "CppScripts.h" #include "CDClientDatabase.h" diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 1214c951..a81fec70 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -20,7 +20,6 @@ #include "WorldPackets.h" #include "Item.h" #include "ZCompression.h" -#include "Player.h" #include "dConfig.h" #include "TeamManager.h" #include "ChatPackets.h" @@ -2584,6 +2583,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //We need to get a new ID for our model first: ObjectIDManager::RequestPersistentID([=](uint32_t newID) { + if (!entity || !entity->GetCharacter() || !entity->GetCharacter()->GetParentUser()) return; LWOOBJID newIDL = newID; GeneralUtils::SetBit(newIDL, eObjectBits::CHARACTER); GeneralUtils::SetBit(newIDL, eObjectBits::PERSISTENT); @@ -2606,7 +2606,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //Insert into ugc: std::string str(sd0Data.get(), sd0Size); std::istringstream sd0DataStream(str); - Database::Get()->InsertNewUgcModel(sd0DataStream, blueprintIDSmall, entity->GetParentUser()->GetAccountID(), entity->GetCharacter()->GetID()); + Database::Get()->InsertNewUgcModel(sd0DataStream, blueprintIDSmall, entity->GetCharacter()->GetParentUser()->GetAccountID(), entity->GetCharacter()->GetID()); //Insert into the db as a BBB model: IPropertyContents::Model model; @@ -5110,13 +5110,8 @@ void GameMessages::HandleSetFlag(RakNet::BitStream* inStream, Entity* entity) { inStream->Read(bFlag); inStream->Read(iFlagID); - auto user = entity->GetParentUser(); - if (user) { - auto character = user->GetLastUsedChar(); - if (!character) return; - - character->SetPlayerFlag(iFlagID, bFlag); - } + auto character = entity->GetCharacter(); + if (character) character->SetPlayerFlag(iFlagID, bFlag); } void GameMessages::HandleRespondToMission(RakNet::BitStream* inStream, Entity* entity) { diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index 6799b834..40ab0688 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -24,6 +24,7 @@ #include "eMissionTaskType.h" #include "eMissionLockState.h" #include "eReplicaComponentType.h" +#include "Character.h" #include "CDMissionEmailTable.h" @@ -208,8 +209,8 @@ Entity* Mission::GetAssociate() const { return m_MissionComponent->GetParent(); } -User* Mission::GetUser() const { - return GetAssociate()->GetParentUser(); +Character* Mission::GetCharacter() const { + return GetAssociate()->GetCharacter(); } uint32_t Mission::GetMissionId() const { @@ -390,7 +391,7 @@ void Mission::Catchup() { if (type == eMissionTaskType::PLAYER_FLAG) { for (int32_t target : task->GetAllTargets()) { - const auto flag = GetUser()->GetLastUsedChar()->GetPlayerFlag(target); + const auto flag = GetCharacter()->GetPlayerFlag(target); if (!flag) { continue; @@ -413,7 +414,7 @@ void Mission::YieldRewards() { return; } - auto* character = GetUser()->GetLastUsedChar(); + auto* character = GetCharacter(); auto* inventoryComponent = entity->GetComponent(); auto* levelComponent = entity->GetComponent(); @@ -599,8 +600,10 @@ void Mission::SetMissionState(const eMissionState state, const bool sendingRewar if (entity == nullptr) { return; } + auto* characterComponent = entity->GetComponent(); + if (!characterComponent) return; - GameMessages::SendNotifyMission(entity, entity->GetParentUser()->GetSystemAddress(), info.id, static_cast(state), sendingRewards); + GameMessages::SendNotifyMission(entity, characterComponent->GetSystemAddress(), info.id, static_cast(state), sendingRewards); } void Mission::SetMissionTypeState(eMissionLockState state, const std::string& type, const std::string& subType) { diff --git a/dGame/dMission/Mission.h b/dGame/dMission/Mission.h index f7c17003..d8c104e8 100644 --- a/dGame/dMission/Mission.h +++ b/dGame/dMission/Mission.h @@ -17,6 +17,7 @@ namespace tinyxml2 { enum class eMissionState : int; enum class eMissionLockState : int; class MissionComponent; +class Character; /** * A mission (or achievement) that a player may unlock, progress and complete. @@ -46,7 +47,7 @@ public: * Returns the account owns the entity that is currently progressing this mission * @return the account owns the entity that is currently progressing this mission */ - User* GetUser() const; + Character* GetCharacter() const; /** * Returns the current state of this mission diff --git a/dGame/dPropertyBehaviors/ControlBehaviors.cpp b/dGame/dPropertyBehaviors/ControlBehaviors.cpp index c541257c..5fee358d 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviors.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviors.cpp @@ -13,6 +13,7 @@ #include "User.h" #include "tinyxml2.h" #include "CDClientDatabase.h" +#include "CharacterComponent.h" // Message includes #include "Action.h" @@ -145,10 +146,12 @@ void ControlBehaviors::ProcessCommand(Entity* modelEntity, const SystemAddress& } else if (command == "moveToInventory") { MoveToInventoryMessage msg(arguments); context.modelComponent->MoveToInventory(msg); + auto* characterComponent = modelOwner->GetComponent(); + if (!characterComponent) return; AMFArrayValue args; args.Insert("BehaviorID", std::to_string(msg.GetBehaviorId())); - GameMessages::SendUIMessageServerToSingleClient(modelOwner, modelOwner->GetParentUser()->GetSystemAddress(), "BehaviorRemoved", args); + GameMessages::SendUIMessageServerToSingleClient(modelOwner, characterComponent->GetSystemAddress(), "BehaviorRemoved", args); SendBehaviorListToClient(context); } else if (command == "updateAction") { diff --git a/dGame/dUtilities/CheatDetection.cpp b/dGame/dUtilities/CheatDetection.cpp index bc50b2cc..a87157a1 100644 --- a/dGame/dUtilities/CheatDetection.cpp +++ b/dGame/dUtilities/CheatDetection.cpp @@ -2,7 +2,6 @@ #include "Database.h" #include "Entity.h" #include "PossessableComponent.h" -#include "Player.h" #include "Game.h" #include "EntityManager.h" #include "Character.h" @@ -59,13 +58,13 @@ void LogAndSaveFailedAntiCheatCheck(const LWOOBJID& id, const SystemAddress& sys player->GetCharacter()->GetName().c_str(), player->GetObjectID(), sysAddr.ToString(), entity->GetCharacter()->GetName().c_str(), entity->GetObjectID()); - toReport = player->GetParentUser(); + if (player->GetCharacter()) toReport = player->GetCharacter()->GetParentUser(); // In the case that the target entity id did not exist, just log the player info. } else if (player) { LOG("Player (%s) (%llu) at system address (%s) with sending player (%llu) does not match their own.", player->GetCharacter()->GetName().c_str(), player->GetObjectID(), sysAddr.ToString(), id); - toReport = player->GetParentUser(); + if (player->GetCharacter()) toReport = player->GetCharacter()->GetParentUser(); // In the rare case that the player does not exist, just log the system address and who the target id was. } else { LOG("Player at system address (%s) with sending player (%llu) does not match their own.", diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 35c5f7a9..0b5133ff 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -53,7 +53,6 @@ #include "Loot.h" #include "EntityInfo.h" #include "LUTriggers.h" -#include "Player.h" #include "PhantomPhysicsComponent.h" #include "ProximityMonitorComponent.h" #include "dpShapeSphere.h" @@ -1017,7 +1016,9 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } } else { - accountId = player->GetParentUser()->GetAccountID(); + auto* character = player->GetCharacter(); + auto* user = character != nullptr ? character->GetParentUser() : nullptr; + if (user) accountId = user->GetAccountID(); characterId = player->GetObjectID(); } @@ -1045,7 +1046,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit expire += 60 * 60 * hours; } - Database::Get()->UpdateAccountUnmuteTime(accountId, expire); + if (accountId != 0) Database::Get()->UpdateAccountUnmuteTime(accountId, expire); char buffer[32] = "brought up for review.\0"; @@ -1109,10 +1110,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } } else { - accountId = player->GetParentUser()->GetAccountID(); + auto* character = player->GetCharacter(); + auto* user = character != nullptr ? character->GetParentUser() : nullptr; + if (user) accountId = user->GetAccountID(); } - Database::Get()->UpdateAccountBan(accountId, true); + if (accountId != 0) Database::Get()->UpdateAccountBan(accountId, true); if (player != nullptr) { Game::server->Disconnect(player->GetSystemAddress(), eServerDisconnectIdentifiers::FREE_TRIAL_EXPIRED); @@ -1423,7 +1426,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } // Allow for this on even while not a GM, as it sometimes toggles incorrrectly. - if (chatCommand == "gminvis" && entity->GetParentUser()->GetMaxGMLevel() >= eGameMasterLevel::DEVELOPER) { + if (chatCommand == "gminvis" && entity->GetCharacter()->GetParentUser()->GetMaxGMLevel() >= eGameMasterLevel::DEVELOPER) { GameMessages::SendToggleGMInvis(entity->GetObjectID(), true, UNASSIGNED_SYSTEM_ADDRESS); return; diff --git a/dScripts/02_server/Map/General/PetDigServer.cpp b/dScripts/02_server/Map/General/PetDigServer.cpp index 0ea78e4f..a55c2f29 100644 --- a/dScripts/02_server/Map/General/PetDigServer.cpp +++ b/dScripts/02_server/Map/General/PetDigServer.cpp @@ -107,7 +107,7 @@ void PetDigServer::HandleXBuildDig(const Entity* self, Entity* owner, Entity* pe return; auto* playerEntity = Game::entityManager->GetEntity(playerID); - if (!playerEntity || !playerEntity->GetParentUser() || !playerEntity->GetParentUser()->GetLastUsedChar()) + if (!playerEntity || !playerEntity->GetCharacter()) return; auto* player = playerEntity->GetCharacter(); diff --git a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp index c8563b53..1952831a 100644 --- a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp +++ b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp @@ -2,7 +2,6 @@ #include "EntityManager.h" #include "GameMessages.h" #include "dZoneManager.h" -#include "Player.h" #include "Character.h" #include "ShootingGalleryComponent.h" #include "PossessorComponent.h" diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 6a8ed074..550fc7ee 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -56,7 +56,6 @@ #include "DestroyableComponent.h" #include "Game.h" #include "MasterPackets.h" -#include "Player.h" #include "PropertyManagementComponent.h" #include "AssetManager.h" #include "LevelProgressionComponent.h" @@ -607,9 +606,10 @@ void HandlePacketChat(Packet* packet) { inStream.Read(expire); auto* entity = Game::entityManager->GetEntity(playerId); - - if (entity != nullptr) { - entity->GetParentUser()->SetMuteExpire(expire); + auto* character = entity != nullptr ? entity->GetCharacter() : nullptr; + auto* user = character != nullptr ? character->GetParentUser() : nullptr; + if (user) { + user->SetMuteExpire(expire); entity->GetCharacter()->SendMuteNotice(); } @@ -1127,9 +1127,10 @@ void HandlePacket(Packet* packet) { //Mail::HandleNotificationRequest(packet->systemAddress, player->GetObjectID()); //Notify chat that a player has loaded: - { - const auto& playerName = player->GetCharacter()->GetName(); - //RakNet::RakString playerName(player->GetCharacter()->GetName().c_str()); + auto* character = player->GetCharacter(); + auto* user = character != nullptr ? character->GetParentUser() : nullptr; + if (user) { + const auto& playerName = character->GetName(); CBITSTREAM; BitStreamUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::PLAYER_ADDED_NOTIFICATION); @@ -1143,7 +1144,7 @@ void HandlePacket(Packet* packet) { bitStream.Write(zone.GetMapID()); bitStream.Write(zone.GetInstanceID()); bitStream.Write(zone.GetCloneID()); - bitStream.Write(player->GetParentUser()->GetMuteExpire()); + bitStream.Write(user->GetMuteExpire()); bitStream.Write(player->GetGMLevel()); Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); From 8e2914813740edff09f39e2c42281b1df7b0e245 Mon Sep 17 00:00:00 2001 From: David Markowitz Date: Sun, 4 Feb 2024 16:39:00 -0800 Subject: [PATCH 09/50] actually use clamped value --- dPhysics/dpGrid.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/dPhysics/dpGrid.cpp b/dPhysics/dpGrid.cpp index f498c491..6e38be92 100644 --- a/dPhysics/dpGrid.cpp +++ b/dPhysics/dpGrid.cpp @@ -30,8 +30,8 @@ void dpGrid::Add(dpEntity* entity) { int cellZ = (int)std::round(entity->m_Position.z) / dpGrid::CELL_SIZE + NUM_CELLS / 2; // Clamp values to the range [0, NUM_CELLS - 1] - std::clamp(cellX, 0, NUM_CELLS - 1); - std::clamp(cellZ, 0, NUM_CELLS - 1); + cellX = std::clamp(cellX, 0, NUM_CELLS - 1); + cellZ = std::clamp(cellZ, 0, NUM_CELLS - 1); //Add to cell: m_Cells[cellX][cellZ].push_back(entity); @@ -49,11 +49,11 @@ void dpGrid::Move(dpEntity* entity, float x, float z) { int cellZ = (int)std::round(z) / dpGrid::CELL_SIZE + NUM_CELLS / 2; // Clamp values to the range [0, NUM_CELLS - 1] - std::clamp(cellX, 0, NUM_CELLS - 1); - std::clamp(cellZ, 0, NUM_CELLS - 1); + cellX = std::clamp(cellX, 0, NUM_CELLS - 1); + cellZ = std::clamp(cellZ, 0, NUM_CELLS - 1); - std::clamp(oldCellX, 0, NUM_CELLS - 1); - std::clamp(oldCellZ, 0, NUM_CELLS - 1); + oldCellX = std::clamp(oldCellX, 0, NUM_CELLS - 1); + oldCellZ = std::clamp(oldCellZ, 0, NUM_CELLS - 1); if (oldCellX == cellX && oldCellZ == cellZ) return; @@ -77,8 +77,8 @@ void dpGrid::Delete(dpEntity* entity) { int oldCellZ = (int)std::round(entity->m_Position.z) / dpGrid::CELL_SIZE + NUM_CELLS / 2; // Clamp values to the range [0, NUM_CELLS - 1] - std::clamp(oldCellX, 0, NUM_CELLS - 1); - std::clamp(oldCellZ, 0, NUM_CELLS - 1); + cellX = std::clamp(oldCellX, 0, NUM_CELLS - 1); + cellZ = std::clamp(oldCellZ, 0, NUM_CELLS - 1); auto& cell = m_Cells[oldCellX][oldCellZ]; auto toRemove = std::find(cell.begin(), cell.end(), entity); From a88ef0c3250224bc585067d9cad9d8a7f449e25c Mon Sep 17 00:00:00 2001 From: David Markowitz Date: Sun, 4 Feb 2024 16:44:40 -0800 Subject: [PATCH 10/50] Update dpGrid.cpp --- dPhysics/dpGrid.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dPhysics/dpGrid.cpp b/dPhysics/dpGrid.cpp index 6e38be92..8ec944fd 100644 --- a/dPhysics/dpGrid.cpp +++ b/dPhysics/dpGrid.cpp @@ -77,8 +77,8 @@ void dpGrid::Delete(dpEntity* entity) { int oldCellZ = (int)std::round(entity->m_Position.z) / dpGrid::CELL_SIZE + NUM_CELLS / 2; // Clamp values to the range [0, NUM_CELLS - 1] - cellX = std::clamp(oldCellX, 0, NUM_CELLS - 1); - cellZ = std::clamp(oldCellZ, 0, NUM_CELLS - 1); + oldCellX = std::clamp(oldCellX, 0, NUM_CELLS - 1); + oldCellZ = std::clamp(oldCellZ, 0, NUM_CELLS - 1); auto& cell = m_Cells[oldCellX][oldCellZ]; auto toRemove = std::find(cell.begin(), cell.end(), entity); From 395e5c1c6660bb10e9f33c5e63cb9b33b919b53c Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 6 Feb 2024 06:53:51 -0800 Subject: [PATCH 11/50] Remove transitive include for Detour (#1450) Moves it to the 1 cpp file that uses it and locks down its header. Still compiles and links. --- dNavigation/dNavMesh.cpp | 9 +-------- dNavigation/dNavMesh.h | 30 ++++++++++++------------------ dPhysics/dpWorld.cpp | 2 +- 3 files changed, 14 insertions(+), 27 deletions(-) diff --git a/dNavigation/dNavMesh.cpp b/dNavigation/dNavMesh.cpp index ab9ed2d5..f49dd31e 100644 --- a/dNavigation/dNavMesh.cpp +++ b/dNavigation/dNavMesh.cpp @@ -11,6 +11,7 @@ #include "dZoneManager.h" #include "DluAssert.h" +#include "DetourExtensions.h" dNavMesh::dNavMesh(uint32_t zoneId) { m_ZoneId = zoneId; @@ -30,16 +31,8 @@ dNavMesh::dNavMesh(uint32_t zoneId) { dNavMesh::~dNavMesh() { // Clean up Recast information - if(m_Solid) rcFreeHeightField(m_Solid); - if (m_CHF) rcFreeCompactHeightfield(m_CHF); - if (m_CSet) rcFreeContourSet(m_CSet); - if (m_PMesh) rcFreePolyMesh(m_PMesh); - if (m_PMDMesh) rcFreePolyMeshDetail(m_PMDMesh); if (m_NavMesh) dtFreeNavMesh(m_NavMesh); if (m_NavQuery) dtFreeNavMeshQuery(m_NavQuery); - - if (m_Ctx) delete m_Ctx; - if (m_Triareas) delete[] m_Triareas; } diff --git a/dNavigation/dNavMesh.h b/dNavigation/dNavMesh.h index 600b8b86..8a55c649 100644 --- a/dNavigation/dNavMesh.h +++ b/dNavigation/dNavMesh.h @@ -2,13 +2,17 @@ #include #include -#include -#include -#include - -#include "DetourExtensions.h" class NiPoint3; +class rcHeightfield; +class rcCompactHeightfield; +class rcContourSet; +class rcPolyMesh; +class rcPolyMeshDetail; +class InputGeom; +class dtNavMesh; +class dtNavMeshQuery; +class rcContext; class dNavMesh { public: @@ -26,24 +30,14 @@ public: float GetHeightAtPoint(const NiPoint3& location, const float halfExtentsHeight = 32.0f) const; std::vector GetPath(const NiPoint3& startPos, const NiPoint3& endPos, float speed = 10.0f); - class dtNavMesh* GetdtNavMesh() { return m_NavMesh; } + bool IsNavmeshLoaded() { return m_NavMesh != nullptr; } private: void LoadNavmesh(); uint32_t m_ZoneId; - uint8_t* m_Triareas = nullptr; - rcHeightfield* m_Solid = nullptr; - rcCompactHeightfield* m_CHF = nullptr; - rcContourSet* m_CSet = nullptr; - rcPolyMesh* m_PMesh = nullptr; - rcConfig m_Config; - rcPolyMeshDetail* m_PMDMesh = nullptr; - - class InputGeom* m_Geometry = nullptr; - class dtNavMesh* m_NavMesh = nullptr; - class dtNavMeshQuery* m_NavQuery = nullptr; + dtNavMesh* m_NavMesh = nullptr; + dtNavMeshQuery* m_NavQuery = nullptr; uint8_t m_NavMeshDrawFlags; - rcContext* m_Ctx = nullptr; }; diff --git a/dPhysics/dpWorld.cpp b/dPhysics/dpWorld.cpp index e820eac2..4ed54858 100644 --- a/dPhysics/dpWorld.cpp +++ b/dPhysics/dpWorld.cpp @@ -81,7 +81,7 @@ void dpWorld::Shutdown() { } bool dpWorld::IsLoaded() { - return m_NavMesh->GetdtNavMesh() != nullptr; + return m_NavMesh->IsNavmeshLoaded(); } void dpWorld::StepWorld(float deltaTime) { From dc29f5962dd43a652fd5549ce6ed154b7f0fbbaf Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 8 Feb 2024 21:40:43 -0800 Subject: [PATCH 12/50] Move CDClientManager to be a namespace (#1431) Tested that worlds still load data as expected. Had no use being a singleton anyways. --- dDatabase/CDClientDatabase/CDClientManager.h | 5 +-- .../CDClientTables/CDLootTableTable.cpp | 4 +- dGame/Entity.cpp | 22 +++++------ dGame/LeaderboardManager.cpp | 2 +- dGame/dBehaviors/Behavior.cpp | 10 ++--- dGame/dBehaviors/OverTimeBehavior.cpp | 2 +- dGame/dComponents/ActivityComponent.cpp | 10 ++--- dGame/dComponents/BaseCombatAIComponent.cpp | 4 +- dGame/dComponents/BuffComponent.cpp | 2 +- dGame/dComponents/CharacterComponent.cpp | 2 +- dGame/dComponents/DestroyableComponent.cpp | 4 +- dGame/dComponents/InventoryComponent.cpp | 18 ++++----- .../dComponents/LevelProgressionComponent.cpp | 2 +- dGame/dComponents/MissionComponent.cpp | 10 ++--- dGame/dComponents/MissionOfferComponent.cpp | 4 +- dGame/dComponents/MovementAIComponent.cpp | 4 +- dGame/dComponents/PetComponent.cpp | 2 +- dGame/dComponents/PhantomPhysicsComponent.cpp | 8 ++-- .../dComponents/PropertyEntranceComponent.cpp | 2 +- dGame/dComponents/RacingControlComponent.cpp | 2 +- dGame/dComponents/RailActivatorComponent.cpp | 2 +- dGame/dComponents/RenderComponent.cpp | 4 +- dGame/dComponents/SkillComponent.cpp | 2 +- dGame/dComponents/VendorComponent.cpp | 12 +++--- dGame/dGameMessages/GameMessageHandler.cpp | 2 +- dGame/dGameMessages/GameMessages.cpp | 16 ++++---- dGame/dGameMessages/PropertyDataMessage.cpp | 2 +- dGame/dInventory/Inventory.cpp | 6 +-- dGame/dInventory/Item.cpp | 10 ++--- dGame/dInventory/ItemSet.cpp | 4 +- dGame/dMission/Mission.cpp | 10 ++--- dGame/dMission/MissionPrerequisites.cpp | 2 +- dGame/dUtilities/Loot.cpp | 38 +++++++++---------- dGame/dUtilities/SlashCommandHandler.cpp | 4 +- dMasterServer/InstanceManager.cpp | 4 +- dMasterServer/MasterServer.cpp | 11 ------ .../02_server/Map/General/QbEnemyStunner.cpp | 4 +- .../FireFirstSkillonStartup.cpp | 4 +- dWorldServer/PerformanceManager.cpp | 2 +- dWorldServer/WorldServer.cpp | 2 +- dZoneManager/Level.cpp | 2 +- dZoneManager/Zone.cpp | 2 +- dZoneManager/dZoneManager.cpp | 4 +- tests/dGameTests/GameDependencies.h | 2 +- 44 files changed, 128 insertions(+), 142 deletions(-) diff --git a/dDatabase/CDClientDatabase/CDClientManager.h b/dDatabase/CDClientDatabase/CDClientManager.h index ae628a36..21a6e3cd 100644 --- a/dDatabase/CDClientDatabase/CDClientManager.h +++ b/dDatabase/CDClientDatabase/CDClientManager.h @@ -9,10 +9,7 @@ /** * Initialize the CDClient tables so they are all loaded into memory. */ -class CDClientManager : public Singleton { -public: - CDClientManager() = default; - +namespace CDClientManager { void LoadValuesFromDatabase(); void LoadValuesFromDefaults(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp index a90f8108..7d04db13 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp @@ -6,8 +6,8 @@ // Sort the tables by their rarity so the highest rarity items are first. void SortTable(LootTableEntries& table) { - auto* componentsRegistryTable = CDClientManager::Instance().GetTable(); - auto* itemComponentTable = CDClientManager::Instance().GetTable(); + auto* componentsRegistryTable = CDClientManager::GetTable(); + auto* itemComponentTable = CDClientManager::GetTable(); // We modify the table in place so the outer loop keeps track of what is sorted // and the inner loop finds the highest rarity item and swaps it with the current position // of the outer loop. diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 50ef5df2..84bdca21 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -215,7 +215,7 @@ void Entity::Initialize() { } // Get the registry table - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); /** * Special case for BBB models. They have components not corresponding to the registry. @@ -369,7 +369,7 @@ void Entity::Initialize() { if (quickBuildComponentID > 0) componentID = quickBuildComponentID; if (buffComponentID > 0) componentID = buffComponentID; - CDDestructibleComponentTable* destCompTable = CDClientManager::Instance().GetTable(); + CDDestructibleComponentTable* destCompTable = CDClientManager::GetTable(); std::vector destCompData = destCompTable->Query([=](CDDestructibleComponent entry) { return (entry.id == componentID); }); bool isSmashable = GetVarAs(u"is_smashable") != 0; @@ -404,7 +404,7 @@ void Entity::Initialize() { uint32_t npcMinLevel = destCompData[0].level; uint32_t currencyIndex = destCompData[0].CurrencyIndex; - CDCurrencyTableTable* currencyTable = CDClientManager::Instance().GetTable(); + CDCurrencyTableTable* currencyTable = CDClientManager::GetTable(); std::vector currencyValues = currencyTable->Query([=](CDCurrencyTable entry) { return (entry.currencyIndex == currencyIndex && entry.npcminlevel == npcMinLevel); }); if (currencyValues.size() > 0) { @@ -489,7 +489,7 @@ void Entity::Initialize() { * This is a bit of a mess */ - CDScriptComponentTable* scriptCompTable = CDClientManager::Instance().GetTable(); + CDScriptComponentTable* scriptCompTable = CDClientManager::GetTable(); int32_t scriptComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::SCRIPT, -1); std::string scriptName = ""; @@ -538,7 +538,7 @@ void Entity::Initialize() { // ZoneControl script if (m_TemplateID == 2365) { - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); const auto zoneID = Game::zoneManager->GetZoneID(); const CDZoneTable* zoneData = zoneTable->Query(zoneID.GetMapID()); @@ -561,7 +561,7 @@ void Entity::Initialize() { if (int componentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::QUICK_BUILD) > 0) { auto* quickBuildComponent = AddComponent(); - CDRebuildComponentTable* rebCompTable = CDClientManager::Instance().GetTable(); + CDRebuildComponentTable* rebCompTable = CDClientManager::GetTable(); std::vector rebCompData = rebCompTable->Query([=](CDRebuildComponent entry) { return (entry.id == quickBuildComponentID); }); if (rebCompData.size() > 0) { @@ -685,7 +685,7 @@ void Entity::Initialize() { int movementAIID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::MOVEMENT_AI); if (movementAIID > 0) { - CDMovementAIComponentTable* moveAITable = CDClientManager::Instance().GetTable(); + CDMovementAIComponentTable* moveAITable = CDClientManager::GetTable(); std::vector moveAIComp = moveAITable->Query([=](CDMovementAIComponent entry) {return (entry.id == movementAIID); }); if (moveAIComp.size() > 0) { @@ -749,7 +749,7 @@ void Entity::Initialize() { int proximityMonitorID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::PROXIMITY_MONITOR); if (proximityMonitorID > 0) { - CDProximityMonitorComponentTable* proxCompTable = CDClientManager::Instance().GetTable(); + CDProximityMonitorComponentTable* proxCompTable = CDClientManager::GetTable(); std::vector proxCompData = proxCompTable->Query([=](CDProximityMonitorComponent entry) { return (entry.id == proximityMonitorID); }); if (proxCompData.size() > 0) { std::vector proximityStr = GeneralUtils::SplitString(proxCompData[0].Proximities, ','); @@ -1665,7 +1665,7 @@ void Entity::PickupItem(const LWOOBJID& objectID) { auto* characterComponent = GetComponent(); if (!inv || !characterComponent) return; - CDObjectsTable* objectsTable = CDClientManager::Instance().GetTable(); + CDObjectsTable* objectsTable = CDClientManager::GetTable(); auto& droppedLoot = characterComponent->GetDroppedLoot(); @@ -1678,10 +1678,10 @@ void Entity::PickupItem(const LWOOBJID& objectID) { const CDObjects& object = objectsTable->GetByID(p.second.lot); if (object.id != 0 && object.type == "Powerup") { - CDObjectSkillsTable* skillsTable = CDClientManager::Instance().GetTable(); + CDObjectSkillsTable* skillsTable = CDClientManager::GetTable(); std::vector skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == p.second.lot); }); for (CDObjectSkills skill : skills) { - CDSkillBehaviorTable* skillBehTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillBehTable = CDClientManager::GetTable(); CDSkillBehavior behaviorData = skillBehTable->GetSkillByID(skill.skillID); SkillComponent::HandleUnmanaged(behaviorData.behaviorID, GetObjectID()); diff --git a/dGame/LeaderboardManager.cpp b/dGame/LeaderboardManager.cpp index 1fd49d26..ba9055a7 100644 --- a/dGame/LeaderboardManager.cpp +++ b/dGame/LeaderboardManager.cpp @@ -402,7 +402,7 @@ Leaderboard::Type LeaderboardManager::GetLeaderboardType(const GameID gameID) { auto lookup = leaderboardCache.find(gameID); if (lookup != leaderboardCache.end()) return lookup->second; - auto* activitiesTable = CDClientManager::Instance().GetTable(); + auto* activitiesTable = CDClientManager::GetTable(); std::vector activities = activitiesTable->Query([gameID](const CDActivities& entry) { return entry.ActivityID == gameID; }); diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index c70b34c7..64bb03f5 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -82,7 +82,7 @@ CDBehaviorParameterTable* Behavior::BehaviorParameterTable = nullptr; Behavior* Behavior::GetBehavior(const uint32_t behaviorId) { if (BehaviorParameterTable == nullptr) { - BehaviorParameterTable = CDClientManager::Instance().GetTable(); + BehaviorParameterTable = CDClientManager::GetTable(); } const auto pair = Cache.find(behaviorId); @@ -297,7 +297,7 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) { } BehaviorTemplates Behavior::GetBehaviorTemplate(const uint32_t behaviorId) { - auto behaviorTemplateTable = CDClientManager::Instance().GetTable(); + auto behaviorTemplateTable = CDClientManager::GetTable(); BehaviorTemplates templateID = BehaviorTemplates::BEHAVIOR_EMPTY; // Find behavior template by its behavior id. Default to 0. @@ -405,7 +405,7 @@ void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID } Behavior::Behavior(const uint32_t behaviorId) { - auto behaviorTemplateTable = CDClientManager::Instance().GetTable(); + auto behaviorTemplateTable = CDClientManager::GetTable(); CDBehaviorTemplate templateInDatabase{}; @@ -448,7 +448,7 @@ Behavior::Behavior(const uint32_t behaviorId) { float Behavior::GetFloat(const std::string& name, const float defaultValue) const { // Get the behavior parameter entry and return its value. - if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance().GetTable(); + if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::GetTable(); return BehaviorParameterTable->GetValue(this->m_behaviorId, name, defaultValue); } @@ -476,7 +476,7 @@ Behavior* Behavior::GetAction(float value) const { std::map Behavior::GetParameterNames() const { std::map templatesInDatabase; // Find behavior template by its behavior id. - if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance().GetTable(); + if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::GetTable(); if (BehaviorParameterTable) { templatesInDatabase = BehaviorParameterTable->GetParametersByBehaviorID(this->m_behaviorId); } diff --git a/dGame/dBehaviors/OverTimeBehavior.cpp b/dGame/dBehaviors/OverTimeBehavior.cpp index bdef2eb6..f66a5253 100644 --- a/dGame/dBehaviors/OverTimeBehavior.cpp +++ b/dGame/dBehaviors/OverTimeBehavior.cpp @@ -41,7 +41,7 @@ void OverTimeBehavior::Load() { m_Action = GetInt("action"); // Since m_Action is a skillID and not a behavior, get is correlated behaviorID. - CDSkillBehaviorTable* skillTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillTable = CDClientManager::GetTable(); m_ActionBehaviorId = skillTable->GetSkillByID(m_Action).behaviorID; m_Delay = GetFloat("delay"); diff --git a/dGame/dComponents/ActivityComponent.cpp b/dGame/dComponents/ActivityComponent.cpp index 60a95952..376251d2 100644 --- a/dGame/dComponents/ActivityComponent.cpp +++ b/dGame/dComponents/ActivityComponent.cpp @@ -46,7 +46,7 @@ ActivityComponent::ActivityComponent(Entity* parent, int32_t activityID) : Compo if (destroyableComponent) { // First lookup the loot matrix id for this component id. - CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance().GetTable(); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::GetTable(); std::vector activityRewards = activityRewardsTable->Query([=](CDActivityRewards entry) {return (entry.LootMatrixIndex == destroyableComponent->GetLootMatrixID()); }); uint32_t startingLMI = 0; @@ -70,7 +70,7 @@ ActivityComponent::ActivityComponent(Entity* parent, int32_t activityID) : Compo } } void ActivityComponent::LoadActivityData(const int32_t activityId) { - CDActivitiesTable* activitiesTable = CDClientManager::Instance().GetTable(); + CDActivitiesTable* activitiesTable = CDClientManager::GetTable(); std::vector activities = activitiesTable->Query([activityId](CDActivities entry) {return (entry.ActivityID == activityId); }); bool soloRacing = Game::config->GetValue("solo_racing") == "1"; @@ -106,7 +106,7 @@ void ActivityComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIniti } void ActivityComponent::ReloadConfig() { - CDActivitiesTable* activitiesTable = CDClientManager::Instance().GetTable(); + CDActivitiesTable* activitiesTable = CDClientManager::GetTable(); std::vector activities = activitiesTable->Query([this](CDActivities entry) {return (entry.ActivityID == m_ActivityID); }); for (auto activity : activities) { auto mapID = m_ActivityInfo.instanceMapID; @@ -545,14 +545,14 @@ void ActivityInstance::RewardParticipant(Entity* participant) { } // First, get the activity data - auto* activityRewardsTable = CDClientManager::Instance().GetTable(); + auto* activityRewardsTable = CDClientManager::GetTable(); std::vector activityRewards = activityRewardsTable->Query([this](CDActivityRewards entry) { return (entry.objectTemplate == m_ActivityInfo.ActivityID); }); if (!activityRewards.empty()) { uint32_t minCoins = 0; uint32_t maxCoins = 0; - auto* currencyTableTable = CDClientManager::Instance().GetTable(); + auto* currencyTableTable = CDClientManager::GetTable(); std::vector currencyTable = currencyTableTable->Query([=](CDCurrencyTable entry) { return (entry.currencyIndex == activityRewards[0].CurrencyIndex && entry.npcminlevel == 1); }); if (!currencyTable.empty()) { diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 21909d5f..17183409 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -107,10 +107,10 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id): int32_t collisionGroup = (COLLISION_GROUP_DYNAMIC | COLLISION_GROUP_ENEMY); - CDComponentsRegistryTable* componentRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentRegistryTable = CDClientManager::GetTable(); auto componentID = componentRegistryTable->GetByIDAndType(parent->GetLOT(), eReplicaComponentType::CONTROLLABLE_PHYSICS); - CDPhysicsComponentTable* physicsComponentTable = CDClientManager::Instance().GetTable(); + CDPhysicsComponentTable* physicsComponentTable = CDClientManager::GetTable(); if (physicsComponentTable != nullptr) { auto* info = physicsComponentTable->GetByID(componentID); diff --git a/dGame/dComponents/BuffComponent.cpp b/dGame/dComponents/BuffComponent.cpp index 10ac4ebb..cdf1d5bc 100644 --- a/dGame/dComponents/BuffComponent.cpp +++ b/dGame/dComponents/BuffComponent.cpp @@ -164,7 +164,7 @@ void BuffComponent::ApplyBuff(const int32_t id, const float duration, const LWOO const auto& parameters = GetBuffParameters(id); for (const auto& parameter : parameters) { if (parameter.name == "overtime") { - auto* behaviorTemplateTable = CDClientManager::Instance().GetTable(); + auto* behaviorTemplateTable = CDClientManager::GetTable(); behaviorID = behaviorTemplateTable->GetSkillByID(parameter.values[0]).behaviorID; stacks = static_cast(parameter.values[1]); diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index 61b744f1..e4e2ba4b 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -770,7 +770,7 @@ void CharacterComponent::AwardClaimCodes() { auto rewardCodes = Database::Get()->GetRewardCodesByAccountID(user->GetAccountID()); if (rewardCodes.empty()) return; - auto* cdrewardCodes = CDClientManager::Instance().GetTable(); + auto* cdrewardCodes = CDClientManager::GetTable(); for (auto const rewardCode : rewardCodes) { LOG_DEBUG("Processing RewardCode %i", rewardCode); const uint32_t rewardCodeIndex = rewardCode >> 6; diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index fd89da4d..68271f26 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -81,7 +81,7 @@ DestroyableComponent::~DestroyableComponent() { } void DestroyableComponent::Reinitialize(LOT templateID) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); int32_t buffComponentID = compRegistryTable->GetByIDAndType(templateID, eReplicaComponentType::BUFF); int32_t collectibleComponentID = compRegistryTable->GetByIDAndType(templateID, eReplicaComponentType::COLLECTIBLE); @@ -92,7 +92,7 @@ void DestroyableComponent::Reinitialize(LOT templateID) { if (quickBuildComponentID > 0) componentID = quickBuildComponentID; if (buffComponentID > 0) componentID = buffComponentID; - CDDestructibleComponentTable* destCompTable = CDClientManager::Instance().GetTable(); + CDDestructibleComponentTable* destCompTable = CDClientManager::GetTable(); std::vector destCompData = destCompTable->Query([=](CDDestructibleComponent entry) { return (entry.id == componentID); }); if (componentID > 0) { diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 97c1198b..591e0505 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -55,10 +55,10 @@ InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* do return; } - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); const auto componentId = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::INVENTORY); - auto* inventoryComponentTable = CDClientManager::Instance().GetTable(); + auto* inventoryComponentTable = CDClientManager::GetTable(); auto items = inventoryComponentTable->Query([=](const CDInventoryComponent entry) { return entry.id == componentId; }); auto slot = 0u; @@ -909,11 +909,11 @@ void InventoryComponent::UnEquipItem(Item* item) { void InventoryComponent::EquipScripts(Item* equippedItem) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); if (!compRegistryTable) return; int32_t scriptComponentID = compRegistryTable->GetByIDAndType(equippedItem->GetLot(), eReplicaComponentType::SCRIPT, -1); if (scriptComponentID > -1) { - CDScriptComponentTable* scriptCompTable = CDClientManager::Instance().GetTable(); + CDScriptComponentTable* scriptCompTable = CDClientManager::GetTable(); CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID); auto* itemScript = CppScripts::GetScript(m_Parent, scriptCompData.script_name); if (!itemScript) { @@ -924,11 +924,11 @@ void InventoryComponent::EquipScripts(Item* equippedItem) { } void InventoryComponent::UnequipScripts(Item* unequippedItem) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); if (!compRegistryTable) return; int32_t scriptComponentID = compRegistryTable->GetByIDAndType(unequippedItem->GetLot(), eReplicaComponentType::SCRIPT, -1); if (scriptComponentID > -1) { - CDScriptComponentTable* scriptCompTable = CDClientManager::Instance().GetTable(); + CDScriptComponentTable* scriptCompTable = CDClientManager::GetTable(); CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID); auto* itemScript = CppScripts::GetScript(m_Parent, scriptCompData.script_name); if (!itemScript) { @@ -1280,7 +1280,7 @@ bool InventoryComponent::IsTransferInventory(eInventoryType type) { } uint32_t InventoryComponent::FindSkill(const LOT lot) { - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto results = table->Query([=](const CDObjectSkills& entry) { return entry.objectTemplate == static_cast(lot); @@ -1298,8 +1298,8 @@ uint32_t InventoryComponent::FindSkill(const LOT lot) { std::vector InventoryComponent::FindBuffs(Item* item, bool castOnEquip) const { std::vector buffs; if (item == nullptr) return buffs; - auto* table = CDClientManager::Instance().GetTable(); - auto* behaviors = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); + auto* behaviors = CDClientManager::GetTable(); const auto results = table->Query([=](const CDObjectSkills& entry) { return entry.objectTemplate == static_cast(item->GetLot()); diff --git a/dGame/dComponents/LevelProgressionComponent.cpp b/dGame/dComponents/LevelProgressionComponent.cpp index 3a18b19c..d271f97b 100644 --- a/dGame/dComponents/LevelProgressionComponent.cpp +++ b/dGame/dComponents/LevelProgressionComponent.cpp @@ -44,7 +44,7 @@ void LevelProgressionComponent::Serialize(RakNet::BitStream* outBitStream, bool } void LevelProgressionComponent::HandleLevelUp() { - auto* rewardsTable = CDClientManager::Instance().GetTable(); + auto* rewardsTable = CDClientManager::GetTable(); const auto& rewards = rewardsTable->GetByLevelID(m_Level); bool rewardingItem = rewards.size() > 0; diff --git a/dGame/dComponents/MissionComponent.cpp b/dGame/dComponents/MissionComponent.cpp index 7219589a..151fcf2f 100644 --- a/dGame/dComponents/MissionComponent.cpp +++ b/dGame/dComponents/MissionComponent.cpp @@ -266,7 +266,7 @@ void MissionComponent::ForceProgressValue(uint32_t missionId, uint32_t taskType, } bool MissionComponent::GetMissionInfo(uint32_t missionId, CDMissions& result) { - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionsTable = CDClientManager::GetTable(); const auto missions = missionsTable->Query([=](const CDMissions& entry) { return entry.id == static_cast(missionId); @@ -320,8 +320,8 @@ const std::vector MissionComponent::LookForAchievements(eMissionTaskTy return acceptedAchievements; #else - auto* missionTasksTable = CDClientManager::Instance().GetTable(); - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionTasksTable = CDClientManager::GetTable(); + auto* missionsTable = CDClientManager::GetTable(); auto tasks = missionTasksTable->Query([=](const CDMissionTasks& entry) { return entry.taskType == static_cast(type); @@ -407,8 +407,8 @@ const std::vector& MissionComponent::QueryAchievements(eMissionTaskTyp } // Find relevent tables - auto* missionTasksTable = CDClientManager::Instance().GetTable(); - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionTasksTable = CDClientManager::GetTable(); + auto* missionsTable = CDClientManager::GetTable(); std::vector result; diff --git a/dGame/dComponents/MissionOfferComponent.cpp b/dGame/dComponents/MissionOfferComponent.cpp index 25d4a739..7f26ed72 100644 --- a/dGame/dComponents/MissionOfferComponent.cpp +++ b/dGame/dComponents/MissionOfferComponent.cpp @@ -40,7 +40,7 @@ bool OfferedMission::GetAcceptsMission() const { //------------------------ MissionOfferComponent below ------------------------ MissionOfferComponent::MissionOfferComponent(Entity* parent, const LOT parentLot) : Component(parent) { - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); auto value = compRegistryTable->GetByIDAndType(parentLot, eReplicaComponentType::MISSION_OFFER, -1); @@ -48,7 +48,7 @@ MissionOfferComponent::MissionOfferComponent(Entity* parent, const LOT parentLot const uint32_t componentId = value; // Now lookup the missions in the MissionNPCComponent table - auto* missionNpcComponentTable = CDClientManager::Instance().GetTable(); + auto* missionNpcComponentTable = CDClientManager::GetTable(); auto missions = missionNpcComponentTable->Query([=](const CDMissionNPCComponent& entry) { return entry.id == static_cast(componentId); diff --git a/dGame/dComponents/MovementAIComponent.cpp b/dGame/dComponents/MovementAIComponent.cpp index 1332fd07..8377031a 100644 --- a/dGame/dComponents/MovementAIComponent.cpp +++ b/dGame/dComponents/MovementAIComponent.cpp @@ -244,8 +244,8 @@ float MovementAIComponent::GetBaseSpeed(LOT lot) { return it->second; } - CDComponentsRegistryTable* componentRegistryTable = CDClientManager::Instance().GetTable(); - CDPhysicsComponentTable* physicsComponentTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentRegistryTable = CDClientManager::GetTable(); + CDPhysicsComponentTable* physicsComponentTable = CDClientManager::GetTable(); int32_t componentID; CDPhysicsComponent* physicsComponent = nullptr; diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 0c377ac7..1af65b4e 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -71,7 +71,7 @@ std::map PetComponent::petFlags = { }; PetComponent::PetComponent(Entity* parentEntity, uint32_t componentId) : Component{ parentEntity } { - m_PetInfo = CDClientManager::Instance().GetTable()->GetByID(componentId); // TODO: Make reference when safe + m_PetInfo = CDClientManager::GetTable()->GetByID(componentId); // TODO: Make reference when safe m_ComponentId = componentId; m_Interaction = LWOOBJID_EMPTY; diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index 217a02fb..b3021415 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -143,10 +143,10 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : PhysicsCompon */ if (!m_HasCreatedPhysics) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); auto componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::PHANTOM_PHYSICS); - CDPhysicsComponentTable* physComp = CDClientManager::Instance().GetTable(); + CDPhysicsComponentTable* physComp = CDClientManager::GetTable(); if (physComp == nullptr) return; @@ -260,10 +260,10 @@ void PhantomPhysicsComponent::CreatePhysics() { y = m_Parent->GetVar(u"primitiveModelValueY"); z = m_Parent->GetVar(u"primitiveModelValueZ"); } else { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); auto componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::PHANTOM_PHYSICS); - CDPhysicsComponentTable* physComp = CDClientManager::Instance().GetTable(); + CDPhysicsComponentTable* physComp = CDClientManager::GetTable(); if (physComp == nullptr) return; diff --git a/dGame/dComponents/PropertyEntranceComponent.cpp b/dGame/dComponents/PropertyEntranceComponent.cpp index 2bb6ea30..ab3bb5da 100644 --- a/dGame/dComponents/PropertyEntranceComponent.cpp +++ b/dGame/dComponents/PropertyEntranceComponent.cpp @@ -18,7 +18,7 @@ PropertyEntranceComponent::PropertyEntranceComponent(Entity* parent, uint32_t componentID) : Component(parent) { this->propertyQueries = {}; - auto table = CDClientManager::Instance().GetTable(); + auto table = CDClientManager::GetTable(); const auto& entry = table->GetByID(componentID); this->m_MapID = entry.mapID; diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index 824e7f36..f3772aad 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -53,7 +53,7 @@ RacingControlComponent::RacingControlComponent(Entity* parent) if (Game::zoneManager->CheckIfAccessibleZone((worldID / 10) * 10)) m_MainWorld = (worldID / 10) * 10; m_ActivityID = 42; - CDActivitiesTable* activitiesTable = CDClientManager::Instance().GetTable(); + CDActivitiesTable* activitiesTable = CDClientManager::GetTable(); std::vector activities = activitiesTable->Query([=](CDActivities entry) {return (entry.instanceMapID == worldID); }); for (CDActivities activity : activities) m_ActivityID = activity.ActivityID; } diff --git a/dGame/dComponents/RailActivatorComponent.cpp b/dGame/dComponents/RailActivatorComponent.cpp index e0eb035a..f269da49 100644 --- a/dGame/dComponents/RailActivatorComponent.cpp +++ b/dGame/dComponents/RailActivatorComponent.cpp @@ -13,7 +13,7 @@ RailActivatorComponent::RailActivatorComponent(Entity* parent, int32_t componentID) : Component(parent) { m_ComponentID = componentID; - const auto tableData = CDClientManager::Instance().GetTable()->GetEntryByID(componentID);; + const auto tableData = CDClientManager::GetTable()->GetEntryByID(componentID);; m_Path = parent->GetVar(u"rail_path"); m_PathDirection = parent->GetVar(u"rail_path_direction"); diff --git a/dGame/dComponents/RenderComponent.cpp b/dGame/dComponents/RenderComponent.cpp index 449fbc4d..d5866917 100644 --- a/dGame/dComponents/RenderComponent.cpp +++ b/dGame/dComponents/RenderComponent.cpp @@ -27,7 +27,7 @@ RenderComponent::RenderComponent(Entity* const parentEntity, const int32_t compo if (!result.eof()) { auto animationGroupIDs = std::string(result.getStringField("animationGroupIDs", "")); if (!animationGroupIDs.empty()) { - auto* animationsTable = CDClientManager::Instance().GetTable(); + auto* animationsTable = CDClientManager::GetTable(); auto groupIdsSplit = GeneralUtils::SplitString(animationGroupIDs, ','); for (auto& groupId : groupIdsSplit) { int32_t groupIdInt; @@ -165,7 +165,7 @@ float RenderComponent::DoAnimation(Entity* self, const std::string& animation, b auto* renderComponent = self->GetComponent(); if (!renderComponent) return returnlength; - auto* animationsTable = CDClientManager::Instance().GetTable(); + auto* animationsTable = CDClientManager::GetTable(); for (auto& groupId : renderComponent->m_animationGroupIds) { auto animationGroup = animationsTable->GetAnimation(animation, renderComponent->GetLastAnimationName(), groupId); if (animationGroup.FoundData()) { diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index b65c7d21..c43813c1 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -234,7 +234,7 @@ bool SkillComponent::CastSkill(const uint32_t skillId, LWOOBJID target, const LW // if it's not in the cache look it up and cache it if (pair == m_skillBehaviorCache.end()) { - auto skillTable = CDClientManager::Instance().GetTable(); + auto skillTable = CDClientManager::GetTable(); behaviorId = skillTable->GetSkillByID(skillId).behaviorID; m_skillBehaviorCache.insert_or_assign(skillId, behaviorId); } else { diff --git a/dGame/dComponents/VendorComponent.cpp b/dGame/dComponents/VendorComponent.cpp index dfea33df..afa3d013 100644 --- a/dGame/dComponents/VendorComponent.cpp +++ b/dGame/dComponents/VendorComponent.cpp @@ -41,14 +41,14 @@ void VendorComponent::RefreshInventory(bool isCreation) { return; } - auto* lootMatrixTable = CDClientManager::Instance().GetTable(); + auto* lootMatrixTable = CDClientManager::GetTable(); const auto& lootMatrices = lootMatrixTable->GetMatrix(m_LootMatrixID); if (lootMatrices.empty()) return; - auto* lootTableTable = CDClientManager::Instance().GetTable(); - auto* itemComponentTable = CDClientManager::Instance().GetTable(); - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* lootTableTable = CDClientManager::GetTable(); + auto* itemComponentTable = CDClientManager::GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); for (const auto& lootMatrix : lootMatrices) { auto vendorItems = lootTableTable->GetTable(lootMatrix.LootTableIndex); @@ -101,10 +101,10 @@ void VendorComponent::RefreshInventory(bool isCreation) { } void VendorComponent::SetupConstants() { - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); int componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::VENDOR); - auto* vendorComponentTable = CDClientManager::Instance().GetTable(); + auto* vendorComponentTable = CDClientManager::GetTable(); std::vector vendorComps = vendorComponentTable->Query([=](CDVendorComponent entry) { return (entry.id == componentID); }); if (vendorComps.empty()) return; auto vendorData = vendorComps.at(0); diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index 07df3c60..64790e31 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -290,7 +290,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System comp->Progress(eMissionTaskType::USE_SKILL, startSkill.skillID); } - CDSkillBehaviorTable* skillTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillTable = CDClientManager::GetTable(); unsigned int behaviorId = skillTable->GetSkillByID(startSkill.skillID).behaviorID; bool success = false; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index a81fec70..8b4d1f05 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -1116,7 +1116,7 @@ void GameMessages::SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, // Currency and powerups should not sync if (team != nullptr && currency == 0) { - CDObjectsTable* objectsTable = CDClientManager::Instance().GetTable(); + CDObjectsTable* objectsTable = CDClientManager::GetTable(); const CDObjects& object = objectsTable->GetByID(item); @@ -4686,8 +4686,8 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti return; } - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); int itemCompID = compRegistryTable->GetByIDAndType(item, eReplicaComponentType::ITEM); CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); @@ -4778,8 +4778,8 @@ void GameMessages::HandleSellToVendor(RakNet::BitStream* inStream, Entity* entit Item* item = inv->FindItemById(iObjID); if (!item) return; - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); int itemCompID = compRegistryTable->GetByIDAndType(item->GetLot(), eReplicaComponentType::ITEM); CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); @@ -4828,8 +4828,8 @@ void GameMessages::HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* Item* item = inv->FindItemById(iObjID); if (!item) return; - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); int itemCompID = compRegistryTable->GetByIDAndType(item->GetLot(), eReplicaComponentType::ITEM); CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); @@ -5041,7 +5041,7 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) if (emoteID == 0) return; std::string sAnimationName = "deaded"; //Default name in case we fail to get the emote - CDEmoteTableTable* emotes = CDClientManager::Instance().GetTable(); + CDEmoteTableTable* emotes = CDClientManager::GetTable(); if (emotes) { CDEmoteTable* emote = emotes->GetEmote(emoteID); if (emote) sAnimationName = emote->animationName; diff --git a/dGame/dGameMessages/PropertyDataMessage.cpp b/dGame/dGameMessages/PropertyDataMessage.cpp index 29bc8ea9..ab7fe9c3 100644 --- a/dGame/dGameMessages/PropertyDataMessage.cpp +++ b/dGame/dGameMessages/PropertyDataMessage.cpp @@ -103,7 +103,7 @@ void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) con } GameMessages::PropertyDataMessage::PropertyDataMessage(uint32_t mapID) { - const auto propertyTemplate = CDClientManager::Instance().GetTable()->GetByMapID(mapID); + const auto propertyTemplate = CDClientManager::GetTable()->GetByMapID(mapID); TemplateID = propertyTemplate.id; ZoneId = propertyTemplate.mapID; diff --git a/dGame/dInventory/Inventory.cpp b/dGame/dInventory/Inventory.cpp index 4475f77b..35222bea 100644 --- a/dGame/dInventory/Inventory.cpp +++ b/dGame/dInventory/Inventory.cpp @@ -275,9 +275,9 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) { } const CDItemComponent& Inventory::FindItemComponent(const LOT lot) { - auto* registry = CDClientManager::Instance().GetTable(); + auto* registry = CDClientManager::GetTable(); - auto* itemComponents = CDClientManager::Instance().GetTable(); + auto* itemComponents = CDClientManager::GetTable(); const auto componentId = registry->GetByIDAndType(lot, eReplicaComponentType::ITEM); @@ -293,7 +293,7 @@ const CDItemComponent& Inventory::FindItemComponent(const LOT lot) { } bool Inventory::IsValidItem(const LOT lot) { - auto* registry = CDClientManager::Instance().GetTable(); + auto* registry = CDClientManager::GetTable(); const auto componentId = registry->GetByIDAndType(lot, eReplicaComponentType::ITEM); diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 4a13cd92..55b0a2d0 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -247,7 +247,7 @@ bool Item::IsEquipped() const { } bool Item::Consume() { - auto* skillsTable = CDClientManager::Instance().GetTable(); + auto* skillsTable = CDClientManager::GetTable(); auto skills = skillsTable->Query([this](const CDObjectSkills entry) { return entry.objectTemplate == static_cast(lot); @@ -313,12 +313,12 @@ void Item::UseNonEquip(Item* item) { bool success = false; auto inventory = item->GetInventory(); if (inventory && inventory->GetType() == eInventoryType::ITEMS) { - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::PACKAGE); if (packageComponentId == 0) return; - auto* packCompTable = CDClientManager::Instance().GetTable(); + auto* packCompTable = CDClientManager::GetTable(); auto packages = packCompTable->Query([=](const CDPackageComponent entry) {return entry.id == static_cast(packageComponentId); }); auto success = !packages.empty(); @@ -396,7 +396,7 @@ void Item::Disassemble(const eInventoryType inventoryType) { } void Item::DisassembleModel(uint32_t numToDismantle) { - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto componentId = table->GetByIDAndType(GetLot(), eReplicaComponentType::RENDER); @@ -481,7 +481,7 @@ void Item::DisassembleModel(uint32_t numToDismantle) { currentBrick = currentBrick->NextSiblingElement(searchTerm.c_str()); } - auto* brickIDTable = CDClientManager::Instance().GetTable(); + auto* brickIDTable = CDClientManager::GetTable(); // Second iteration actually distributes the bricks for (const auto& [part, count] : parts) { diff --git a/dGame/dInventory/ItemSet.cpp b/dGame/dInventory/ItemSet.cpp index 3364b63b..54db9e9c 100644 --- a/dGame/dInventory/ItemSet.cpp +++ b/dGame/dInventory/ItemSet.cpp @@ -129,7 +129,7 @@ void ItemSet::OnEquip(const LOT lot) { auto* missionComponent = m_InventoryComponent->GetParent()->GetComponent(); for (const auto skill : skillSet) { - auto* skillTable = CDClientManager::Instance().GetTable(); + auto* skillTable = CDClientManager::GetTable(); const auto behaviorId = skillTable->GetSkillByID(skill).behaviorID; @@ -161,7 +161,7 @@ void ItemSet::OnUnEquip(const LOT lot) { const auto& skillComponent = m_InventoryComponent->GetParent()->GetComponent(); for (const auto skill : skillSet) { - auto* skillTable = CDClientManager::Instance().GetTable(); + auto* skillTable = CDClientManager::GetTable(); const auto behaviorId = skillTable->GetSkillByID(skill).behaviorID; diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index 40ab0688..4ed80bf3 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -41,7 +41,7 @@ Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { m_State = eMissionState::UNKNOWN; - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionsTable = CDClientManager::GetTable(); auto* mis = missionsTable->GetPtrByMissionID(missionId); info = *mis; @@ -52,7 +52,7 @@ Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { return; } - auto* tasksTable = CDClientManager::Instance().GetTable(); + auto* tasksTable = CDClientManager::GetTable(); auto tasks = tasksTable->GetByMissionID(missionId); @@ -180,7 +180,7 @@ void Mission::UpdateXml(tinyxml2::XMLElement* element) { } bool Mission::IsValidMission(const uint32_t missionId) { - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto missions = table->Query([=](const CDMissions& entry) { return entry.id == static_cast(missionId); @@ -190,7 +190,7 @@ bool Mission::IsValidMission(const uint32_t missionId) { } bool Mission::IsValidMission(const uint32_t missionId, CDMissions& info) { - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto missions = table->Query([=](const CDMissions& entry) { return entry.id == static_cast(missionId); @@ -334,7 +334,7 @@ void Mission::Complete(const bool yieldRewards) { missionComponent->Progress(eMissionTaskType::RACING, info.id, static_cast(eRacingTaskParam::COMPLETE_TRACK_TASKS)); - auto* missionEmailTable = CDClientManager::Instance().GetTable(); + auto* missionEmailTable = CDClientManager::GetTable(); const auto missionId = GetMissionId(); diff --git a/dGame/dMission/MissionPrerequisites.cpp b/dGame/dMission/MissionPrerequisites.cpp index 89d547fd..b5b81160 100644 --- a/dGame/dMission/MissionPrerequisites.cpp +++ b/dGame/dMission/MissionPrerequisites.cpp @@ -161,7 +161,7 @@ bool MissionPrerequisites::CheckPrerequisites(uint32_t missionId, const std::uno return index->second->Execute(missions); } - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionsTable = CDClientManager::GetTable(); const auto missionEntries = missionsTable->Query([=](const CDMissions& entry) { return entry.id == static_cast(missionId); }); diff --git a/dGame/dUtilities/Loot.cpp b/dGame/dUtilities/Loot.cpp index 25c81e74..b2f96ac3 100644 --- a/dGame/dUtilities/Loot.cpp +++ b/dGame/dUtilities/Loot.cpp @@ -28,11 +28,11 @@ void Loot::CacheMatrix(uint32_t matrixIndex) { return; } CachedMatrices.insert(matrixIndex); - CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); - CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance().GetTable(); - CDLootTableTable* lootTableTable = CDClientManager::Instance().GetTable(); - CDRarityTableTable* rarityTableTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); + CDLootMatrixTable* lootMatrixTable = CDClientManager::GetTable(); + CDLootTableTable* lootTableTable = CDClientManager::GetTable(); + CDRarityTableTable* rarityTableTable = CDClientManager::GetTable(); const auto& matrix = lootMatrixTable->GetMatrix(matrixIndex); @@ -47,11 +47,11 @@ void Loot::CacheMatrix(uint32_t matrixIndex) { } std::unordered_map Loot::RollLootMatrix(Entity* player, uint32_t matrixIndex) { - CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); - CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance().GetTable(); - CDLootTableTable* lootTableTable = CDClientManager::Instance().GetTable(); - CDRarityTableTable* rarityTableTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); + CDLootMatrixTable* lootMatrixTable = CDClientManager::GetTable(); + CDLootTableTable* lootTableTable = CDClientManager::GetTable(); + CDRarityTableTable* rarityTableTable = CDClientManager::GetTable(); auto* missionComponent = player->GetComponent(); std::unordered_map drops; @@ -134,11 +134,11 @@ std::unordered_map Loot::RollLootMatrix(Entity* player, uint32_t m } std::unordered_map Loot::RollLootMatrix(uint32_t matrixIndex) { - CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); - CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance().GetTable(); - CDLootTableTable* lootTableTable = CDClientManager::Instance().GetTable(); - CDRarityTableTable* rarityTableTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); + CDLootMatrixTable* lootMatrixTable = CDClientManager::GetTable(); + CDLootTableTable* lootTableTable = CDClientManager::GetTable(); + CDRarityTableTable* rarityTableTable = CDClientManager::GetTable(); std::unordered_map drops; const auto& matrix = lootMatrixTable->GetMatrix(matrixIndex); @@ -216,7 +216,7 @@ void Loot::GiveLoot(Entity* player, std::unordered_map& result, eL } void Loot::GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating) { - CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance().GetTable(); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::GetTable(); std::vector activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); const CDActivityRewards* selectedReward = nullptr; @@ -232,7 +232,7 @@ void Loot::GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, uint32_t minCoins = 0; uint32_t maxCoins = 0; - CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance().GetTable(); + CDCurrencyTableTable* currencyTableTable = CDClientManager::GetTable(); std::vector currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); if (currencyTable.size() > 0) { @@ -286,7 +286,7 @@ void Loot::DropLoot(Entity* player, Entity* killedObject, std::unordered_map(); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::GetTable(); std::vector activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); const CDActivityRewards* selectedReward = nullptr; @@ -303,7 +303,7 @@ void Loot::DropActivityLoot(Entity* player, Entity* source, uint32_t activityID, uint32_t minCoins = 0; uint32_t maxCoins = 0; - CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance().GetTable(); + CDCurrencyTableTable* currencyTableTable = CDClientManager::GetTable(); std::vector currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); if (currencyTable.size() > 0) { diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 0b5133ff..ef12c396 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -1899,7 +1899,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "setrewardcode" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - auto* cdrewardCodes = CDClientManager::Instance().GetTable(); + auto* cdrewardCodes = CDClientManager::GetTable(); auto id = cdrewardCodes->GetCodeID(args[0]); if (id != -1) Database::Get()->InsertRewardCode(user->GetAccountID(), id); @@ -1960,7 +1960,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit Game::entityManager->SerializeEntity(closest); - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto& info = table->GetByID(closest->GetLOT()); diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index a5a6d8dc..a46ed81a 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -322,7 +322,7 @@ Instance* InstanceManager::FindPrivateInstance(const std::string& password) { } int InstanceManager::GetSoftCap(LWOMAPID mapID) { - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); if (zoneTable) { const CDZoneTable* zone = zoneTable->Query(mapID); @@ -335,7 +335,7 @@ int InstanceManager::GetSoftCap(LWOMAPID mapID) { } int InstanceManager::GetHardCap(LWOMAPID mapID) { - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); if (zoneTable) { const CDZoneTable* zone = zoneTable->Query(mapID); diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index f15bb9a9..749b4130 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -177,17 +177,6 @@ int main(int argc, char** argv) { // Run migrations should any need to be run. MigrationRunner::RunSQLiteMigrations(); - //Get CDClient initial information - try { - CDClientManager::Instance(); - } catch (CppSQLite3Exception& e) { - LOG("Failed to initialize CDServer SQLite Database"); - LOG("May be caused by corrupted file: %s", (Game::assetManager->GetResPath() / "CDServer.sqlite").string().c_str()); - LOG("Error: %s", e.errorMessage()); - LOG("Error Code: %i", e.errorCode()); - return EXIT_FAILURE; - } - //If the first command line argument is -a or --account then make the user //input a username and password, with the password being hidden. if (argc > 1 && diff --git a/dScripts/02_server/Map/General/QbEnemyStunner.cpp b/dScripts/02_server/Map/General/QbEnemyStunner.cpp index 8291f409..2238c410 100644 --- a/dScripts/02_server/Map/General/QbEnemyStunner.cpp +++ b/dScripts/02_server/Map/General/QbEnemyStunner.cpp @@ -17,12 +17,12 @@ void QbEnemyStunner::OnQuickBuildComplete(Entity* self, Entity* target) { if (!skillComponent) return; // Get the skill IDs of this object. - CDObjectSkillsTable* skillsTable = CDClientManager::Instance().GetTable(); + CDObjectSkillsTable* skillsTable = CDClientManager::GetTable(); auto skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == self->GetLOT()); }); std::map skillBehaviorMap; // For each skill, cast it with the associated behavior ID. for (auto skill : skills) { - CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::GetTable(); CDSkillBehavior behaviorData = skillBehaviorTable->GetSkillByID(skill.skillID); skillBehaviorMap.insert(std::make_pair(skill.skillID, behaviorData.behaviorID)); diff --git a/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp b/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp index 389f3621..0220711d 100644 --- a/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp +++ b/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp @@ -11,12 +11,12 @@ void FireFirstSkillonStartup::OnStartup(Entity* self) { if (!skillComponent) return; // Get the skill IDs of this object. - CDObjectSkillsTable* skillsTable = CDClientManager::Instance().GetTable(); + CDObjectSkillsTable* skillsTable = CDClientManager::GetTable(); std::vector skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == self->GetLOT()); }); // For each skill, cast it with the associated behavior ID. for (auto skill : skills) { - CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::GetTable(); CDSkillBehavior behaviorData = skillBehaviorTable->GetSkillByID(skill.skillID); // Should parent entity be null, make the originator self. diff --git a/dWorldServer/PerformanceManager.cpp b/dWorldServer/PerformanceManager.cpp index 248be54a..052d075b 100644 --- a/dWorldServer/PerformanceManager.cpp +++ b/dWorldServer/PerformanceManager.cpp @@ -70,7 +70,7 @@ std::map PerformanceManager::m_Profiles = { void PerformanceManager::SelectProfile(LWOMAPID mapID) { // Try to get it from zoneTable - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); if (zoneTable) { const CDZoneTable* zone = zoneTable->Query(mapID); if (zone) { diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 550fc7ee..6df5d0da 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -180,7 +180,7 @@ int main(int argc, char** argv) { return EXIT_FAILURE; } - CDClientManager::Instance().LoadValuesFromDatabase(); + CDClientManager::LoadValuesFromDatabase(); Diagnostics::SetProduceMemoryDump(Game::config->GetValue("generate_dump") == "1"); diff --git a/dZoneManager/Level.cpp b/dZoneManager/Level.cpp index 0a46dc89..2606b46f 100644 --- a/dZoneManager/Level.cpp +++ b/dZoneManager/Level.cpp @@ -208,7 +208,7 @@ void Level::ReadSceneObjectDataChunk(std::istream& file, Header& header) { uint32_t objectsCount = 0; BinaryIO::BinaryRead(file, objectsCount); - CDFeatureGatingTable* featureGatingTable = CDClientManager::Instance().GetTable(); + CDFeatureGatingTable* featureGatingTable = CDClientManager::GetTable(); CDFeatureGating gating; gating.major = 1; diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index 3f306c05..42ce1215 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -154,7 +154,7 @@ void Zone::LoadZoneIntoMemory() { std::string Zone::GetFilePathForZoneID() { //We're gonna go ahead and presume we've got the db loaded already: - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); const CDZoneTable* zone = zoneTable->Query(this->GetZoneID().GetMapID()); if (zone != nullptr) { std::string toReturn = "maps/" + zone->zoneName; diff --git a/dZoneManager/dZoneManager.cpp b/dZoneManager/dZoneManager.cpp index 3aa35485..09baabed 100644 --- a/dZoneManager/dZoneManager.cpp +++ b/dZoneManager/dZoneManager.cpp @@ -29,7 +29,7 @@ void dZoneManager::Initialize(const LWOZONEID& zoneID) { LOT zoneControlTemplate = 2365; - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); if (zoneTable != nullptr) { const CDZoneTable* zone = zoneTable->Query(zoneID.GetMapID()); @@ -208,7 +208,7 @@ uint32_t dZoneManager::GetUniqueMissionIdStartingValue() { bool dZoneManager::CheckIfAccessibleZone(LWOMAPID zoneID) { //We're gonna go ahead and presume we've got the db loaded already: - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); const CDZoneTable* zone = zoneTable->Query(zoneID); if (zone != nullptr) { return Game::assetManager->HasFile(("maps/" + zone->zoneName).c_str()); diff --git a/tests/dGameTests/GameDependencies.h b/tests/dGameTests/GameDependencies.h index 11c320ba..5d9c99bf 100644 --- a/tests/dGameTests/GameDependencies.h +++ b/tests/dGameTests/GameDependencies.h @@ -36,7 +36,7 @@ protected: Game::entityManager = new EntityManager(); // Create a CDClientManager instance and load from defaults - CDClientManager::Instance().LoadValuesFromDefaults(); + CDClientManager::LoadValuesFromDefaults(); } void TearDownDependencies() { From d2aeebcd46d1b5fbc9177a53915fda898faee1da Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 9 Feb 2024 05:37:58 -0800 Subject: [PATCH 13/50] chore: Move database storage containers to be translation unit local to allow for safe references (#1434) * Move CDClientManager to be a namespace Tested that worlds still load data as expected. Had no use being a singleton anyways. * Move cdclient data storage to tu local containers Allows some data from these containers to be saved on object by reference instead of always needing to copy. iteration 2 - move all unnamed namespace containers to a singular spot - use macro for template specialization and variable declaration - use templates to allow for as little copy paste of types and functions as possible * remember to use typename! compiler believes T::StorageType is accessing a member, not a type. * Update CDClientManager.cpp * move to cpp? --- .../CDClientDatabase/CDClientManager.cpp | 50 +++++++++++++++++++ dDatabase/CDClientDatabase/CDClientManager.h | 34 ++++++++++--- .../CDClientTables/CDActivitiesTable.cpp | 8 +-- .../CDClientTables/CDActivitiesTable.h | 7 +-- .../CDClientTables/CDActivityRewardsTable.cpp | 8 +-- .../CDClientTables/CDActivityRewardsTable.h | 8 +-- .../CDClientTables/CDAnimationsTable.cpp | 31 +++++++----- .../CDClientTables/CDAnimationsTable.h | 20 +++----- .../CDBehaviorParameterTable.cpp | 21 +++++--- .../CDClientTables/CDBehaviorParameterTable.h | 10 ++-- .../CDBehaviorTemplateTable.cpp | 29 ++++------- .../CDClientTables/CDBehaviorTemplateTable.h | 12 +---- .../CDClientTables/CDBrickIDTableTable.cpp | 13 ++--- .../CDClientTables/CDBrickIDTableTable.h | 7 +-- .../CDComponentsRegistryTable.cpp | 22 ++++---- .../CDComponentsRegistryTable.h | 5 +- .../CDClientTables/CDCurrencyTableTable.cpp | 13 ++--- .../CDClientTables/CDCurrencyTableTable.h | 7 +-- .../CDDestructibleComponentTable.cpp | 13 ++--- .../CDDestructibleComponentTable.h | 7 +-- .../CDClientTables/CDEmoteTable.cpp | 2 + .../CDClientTables/CDEmoteTable.h | 5 +- .../CDClientTables/CDFeatureGatingTable.cpp | 14 +++--- .../CDClientTables/CDFeatureGatingTable.h | 7 +-- .../CDInventoryComponentTable.cpp | 13 ++--- .../CDInventoryComponentTable.h | 7 +-- .../CDClientTables/CDItemComponentTable.cpp | 14 +++--- .../CDClientTables/CDItemComponentTable.h | 5 +- .../CDClientTables/CDItemSetSkillsTable.cpp | 14 ++---- .../CDClientTables/CDItemSetSkillsTable.h | 7 +-- .../CDClientTables/CDItemSetsTable.cpp | 12 ++--- .../CDClientTables/CDItemSetsTable.h | 7 +-- .../CDLevelProgressionLookupTable.cpp | 12 ++--- .../CDLevelProgressionLookupTable.h | 7 +-- .../CDClientTables/CDLootMatrixTable.cpp | 14 +++--- .../CDClientTables/CDLootMatrixTable.h | 3 +- .../CDClientTables/CDLootTableTable.cpp | 18 ++++--- .../CDClientTables/CDLootTableTable.h | 3 +- .../CDClientTables/CDMissionEmailTable.cpp | 15 ++---- .../CDClientTables/CDMissionEmailTable.h | 7 +-- .../CDMissionNPCComponentTable.cpp | 13 ++--- .../CDMissionNPCComponentTable.h | 9 +--- .../CDClientTables/CDMissionTasksTable.cpp | 15 +++--- .../CDClientTables/CDMissionTasksTable.h | 8 ++- .../CDClientTables/CDMissionsTable.cpp | 15 +++--- .../CDClientTables/CDMissionsTable.h | 8 +-- .../CDMovementAIComponentTable.cpp | 12 ++--- .../CDMovementAIComponentTable.h | 8 +-- .../CDClientTables/CDObjectSkillsTable.cpp | 11 ++-- .../CDClientTables/CDObjectSkillsTable.h | 9 +--- .../CDClientTables/CDObjectsTable.cpp | 16 ++++-- .../CDClientTables/CDObjectsTable.h | 6 +-- .../CDPackageComponentTable.cpp | 14 ++---- .../CDClientTables/CDPackageComponentTable.h | 7 +-- .../CDClientTables/CDPetComponentTable.cpp | 11 ++-- .../CDClientTables/CDPetComponentTable.h | 5 +- .../CDPhysicsComponentTable.cpp | 8 +-- .../CDClientTables/CDPhysicsComponentTable.h | 5 +- .../CDPropertyEntranceComponentTable.cpp | 12 +++-- .../CDPropertyEntranceComponentTable.h | 8 +-- .../CDPropertyTemplateTable.cpp | 11 ++-- .../CDClientTables/CDPropertyTemplateTable.h | 6 +-- .../CDProximityMonitorComponentTable.cpp | 12 ++--- .../CDProximityMonitorComponentTable.h | 7 +-- .../CDRailActivatorComponent.cpp | 9 ++-- .../CDClientTables/CDRailActivatorComponent.h | 5 +- .../CDClientTables/CDRarityTableTable.cpp | 5 +- .../CDClientTables/CDRarityTableTable.h | 8 ++- .../CDRebuildComponentTable.cpp | 12 ++--- .../CDClientTables/CDRebuildComponentTable.h | 7 +-- .../CDClientTables/CDRewardCodesTable.cpp | 9 ++-- .../CDClientTables/CDRewardCodesTable.h | 6 +-- .../CDClientTables/CDRewardsTable.cpp | 5 +- .../CDClientTables/CDRewardsTable.h | 6 +-- .../CDClientTables/CDScriptComponentTable.cpp | 12 +++-- .../CDClientTables/CDScriptComponentTable.h | 6 +-- .../CDClientTables/CDSkillBehaviorTable.cpp | 16 +++--- .../CDClientTables/CDSkillBehaviorTable.h | 6 +-- .../CDClientDatabase/CDClientTables/CDTable.h | 28 ++++++----- .../CDClientTables/CDVendorComponentTable.cpp | 13 ++--- .../CDClientTables/CDVendorComponentTable.h | 7 +-- .../CDClientTables/CDZoneTableTable.cpp | 4 +- .../CDClientTables/CDZoneTableTable.h | 5 +- dGame/dComponents/RenderComponent.cpp | 7 ++- 84 files changed, 394 insertions(+), 529 deletions(-) diff --git a/dDatabase/CDClientDatabase/CDClientManager.cpp b/dDatabase/CDClientDatabase/CDClientManager.cpp index f270d849..0e05c0b8 100644 --- a/dDatabase/CDClientDatabase/CDClientManager.cpp +++ b/dDatabase/CDClientDatabase/CDClientManager.cpp @@ -39,6 +39,7 @@ #include "CDFeatureGatingTable.h" #include "CDRailActivatorComponent.h" #include "CDRewardCodesTable.h" +#include "CDPetComponentTable.h" #include @@ -61,6 +62,55 @@ public: } }; +// Using a macro to reduce repetitive code and issues from copy and paste. +// As a note, ## in a macro is used to concatenate two tokens together. + +#define SPECIALIZE_TABLE_STORAGE(table) \ + template<> typename table::StorageType& CDClientManager::GetEntriesMutable() { return table##Entries; }; + +#define DEFINE_TABLE_STORAGE(table) namespace { table::StorageType table##Entries; }; SPECIALIZE_TABLE_STORAGE(table) + +DEFINE_TABLE_STORAGE(CDActivityRewardsTable); +DEFINE_TABLE_STORAGE(CDActivitiesTable); +DEFINE_TABLE_STORAGE(CDAnimationsTable); +DEFINE_TABLE_STORAGE(CDBehaviorParameterTable); +DEFINE_TABLE_STORAGE(CDBehaviorTemplateTable); +DEFINE_TABLE_STORAGE(CDBrickIDTableTable); +DEFINE_TABLE_STORAGE(CDComponentsRegistryTable); +DEFINE_TABLE_STORAGE(CDCurrencyTableTable); +DEFINE_TABLE_STORAGE(CDDestructibleComponentTable); +DEFINE_TABLE_STORAGE(CDEmoteTableTable); +DEFINE_TABLE_STORAGE(CDFeatureGatingTable); +DEFINE_TABLE_STORAGE(CDInventoryComponentTable); +DEFINE_TABLE_STORAGE(CDItemComponentTable); +DEFINE_TABLE_STORAGE(CDItemSetSkillsTable); +DEFINE_TABLE_STORAGE(CDItemSetsTable); +DEFINE_TABLE_STORAGE(CDLevelProgressionLookupTable); +DEFINE_TABLE_STORAGE(CDLootMatrixTable); +DEFINE_TABLE_STORAGE(CDLootTableTable); +DEFINE_TABLE_STORAGE(CDMissionEmailTable); +DEFINE_TABLE_STORAGE(CDMissionNPCComponentTable); +DEFINE_TABLE_STORAGE(CDMissionTasksTable); +DEFINE_TABLE_STORAGE(CDMissionsTable); +DEFINE_TABLE_STORAGE(CDMovementAIComponentTable); +DEFINE_TABLE_STORAGE(CDObjectSkillsTable); +DEFINE_TABLE_STORAGE(CDObjectsTable); +DEFINE_TABLE_STORAGE(CDPhysicsComponentTable); +DEFINE_TABLE_STORAGE(CDPackageComponentTable); +DEFINE_TABLE_STORAGE(CDPetComponentTable); +DEFINE_TABLE_STORAGE(CDProximityMonitorComponentTable); +DEFINE_TABLE_STORAGE(CDPropertyEntranceComponentTable); +DEFINE_TABLE_STORAGE(CDPropertyTemplateTable); +DEFINE_TABLE_STORAGE(CDRailActivatorComponentTable); +DEFINE_TABLE_STORAGE(CDRarityTableTable); +DEFINE_TABLE_STORAGE(CDRebuildComponentTable); +DEFINE_TABLE_STORAGE(CDRewardCodesTable); +DEFINE_TABLE_STORAGE(CDRewardsTable); +DEFINE_TABLE_STORAGE(CDScriptComponentTable); +DEFINE_TABLE_STORAGE(CDSkillBehaviorTable); +DEFINE_TABLE_STORAGE(CDVendorComponentTable); +DEFINE_TABLE_STORAGE(CDZoneTableTable); + void CDClientManager::LoadValuesFromDatabase() { if (!CDClientDatabase::isConnected) throw CDClientConnectionException(); diff --git a/dDatabase/CDClientDatabase/CDClientManager.h b/dDatabase/CDClientDatabase/CDClientManager.h index 21a6e3cd..c1c4443d 100644 --- a/dDatabase/CDClientDatabase/CDClientManager.h +++ b/dDatabase/CDClientDatabase/CDClientManager.h @@ -1,8 +1,5 @@ -#pragma once - -#include "CDTable.h" - -#include "Singleton.h" +#ifndef __CDCLIENTMANAGER__H__ +#define __CDCLIENTMANAGER__H__ #define UNUSED_TABLE(v) @@ -20,7 +17,28 @@ namespace CDClientManager { * @return A pointer to the requested table. */ template - T* GetTable() { - return &T::Instance(); - } + T* GetTable(); + + /** + * Fetch a table from CDClient + * Note: Calling this function without a template specialization in CDClientManager.cpp will cause a linker error. + * + * @tparam Table type to fetch + * @return A pointer to the requested table. + */ + template + typename T::StorageType& GetEntriesMutable(); }; + + +// These are included after the CDClientManager namespace declaration as CDTable as of Jan 29 2024 relies on CDClientManager in Templated code. +#include "CDTable.h" + +#include "Singleton.h" + +template +T* CDClientManager::GetTable() { + return &T::Instance(); +}; + +#endif //!__CDCLIENTMANAGER__H__ diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.cpp index 998c4095..19111490 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.cpp @@ -1,5 +1,6 @@ #include "CDActivitiesTable.h" + void CDActivitiesTable::LoadValuesFromDatabase() { // First, get the size of the table uint32_t size = 0; @@ -13,7 +14,8 @@ void CDActivitiesTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Activities"); @@ -39,7 +41,7 @@ void CDActivitiesTable::LoadValuesFromDatabase() { entry.noTeamLootOnDeath = tableData.getIntField("noTeamLootOnDeath", -1); entry.optionalPercentage = tableData.getFloatField("optionalPercentage", -1.0f); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -48,7 +50,7 @@ void CDActivitiesTable::LoadValuesFromDatabase() { std::vector CDActivitiesTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.h index 75fc602e..3e1d4c37 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.h @@ -25,15 +25,10 @@ struct CDActivities { float optionalPercentage; }; -class CDActivitiesTable : public CDTable { -private: - std::vector entries; - +class CDActivitiesTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const { return this->entries; } }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.cpp index 7795a177..abe0c50c 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.cpp @@ -1,5 +1,6 @@ #include "CDActivityRewardsTable.h" + void CDActivityRewardsTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -14,7 +15,8 @@ void CDActivityRewardsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ActivityRewards"); @@ -28,7 +30,7 @@ void CDActivityRewardsTable::LoadValuesFromDatabase() { entry.ChallengeRating = tableData.getIntField("ChallengeRating", -1); entry.description = tableData.getStringField("description", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -37,7 +39,7 @@ void CDActivityRewardsTable::LoadValuesFromDatabase() { std::vector CDActivityRewardsTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.h index 40ab17e7..8d07a718 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.h @@ -13,15 +13,9 @@ struct CDActivityRewards { std::string description; //!< The description }; -class CDActivityRewardsTable : public CDTable { -private: - std::vector entries; - +class CDActivityRewardsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - std::vector GetEntries() const; - }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.cpp index 7244ddee..cf461fc9 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.cpp @@ -5,6 +5,7 @@ void CDAnimationsTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Animations"); + auto& animations = GetEntriesMutable(); while (!tableData.eof()) { std::string animation_type = tableData.getStringField("animation_type", ""); DluAssert(!animation_type.empty()); @@ -24,7 +25,7 @@ void CDAnimationsTable::LoadValuesFromDatabase() { UNUSED_COLUMN(entry.priority = tableData.getFloatField("priority", 0.0f);) UNUSED_COLUMN(entry.blendTime = tableData.getFloatField("blendTime", 0.0f);) - this->animations[CDAnimationKey(animation_type, animationGroupID)].push_back(entry); + animations[CDAnimationKey(animation_type, animationGroupID)].push_back(entry); tableData.nextRow(); } @@ -35,6 +36,7 @@ bool CDAnimationsTable::CacheData(CppSQLite3Statement& queryToCache) { auto tableData = queryToCache.execQuery(); // If we received a bad lookup, cache it anyways so we do not run the query again. if (tableData.eof()) return false; + auto& animations = GetEntriesMutable(); do { std::string animation_type = tableData.getStringField("animation_type", ""); @@ -55,7 +57,7 @@ bool CDAnimationsTable::CacheData(CppSQLite3Statement& queryToCache) { UNUSED_COLUMN(entry.priority = tableData.getFloatField("priority", 0.0f);) UNUSED_COLUMN(entry.blendTime = tableData.getFloatField("blendTime", 0.0f);) - this->animations[CDAnimationKey(animation_type, animationGroupID)].push_back(entry); + animations[CDAnimationKey(animation_type, animationGroupID)].push_back(entry); tableData.nextRow(); } while (!tableData.eof()); @@ -68,15 +70,17 @@ void CDAnimationsTable::CacheAnimations(const CDAnimationKey animationKey) { auto query = CDClientDatabase::CreatePreppedStmt("SELECT * FROM Animations WHERE animationGroupID = ? and animation_type = ?"); query.bind(1, static_cast(animationKey.second)); query.bind(2, animationKey.first.c_str()); + auto& animations = GetEntriesMutable(); // If we received a bad lookup, cache it anyways so we do not run the query again. if (!CacheData(query)) { - this->animations[animationKey]; + animations[animationKey]; } } void CDAnimationsTable::CacheAnimationGroup(AnimationGroupID animationGroupID) { - auto animationEntryCached = this->animations.find(CDAnimationKey("", animationGroupID)); - if (animationEntryCached != this->animations.end()) { + auto& animations = GetEntriesMutable(); + auto animationEntryCached = animations.find(CDAnimationKey("", animationGroupID)); + if (animationEntryCached != animations.end()) { return; } @@ -85,28 +89,29 @@ void CDAnimationsTable::CacheAnimationGroup(AnimationGroupID animationGroupID) { // Cache the query so we don't run the query again. CacheData(query); - this->animations[CDAnimationKey("", animationGroupID)]; + animations[CDAnimationKey("", animationGroupID)]; } -CDAnimationLookupResult CDAnimationsTable::GetAnimation(const AnimationID& animationType, const std::string& previousAnimationName, const AnimationGroupID animationGroupID) { +std::optional CDAnimationsTable::GetAnimation(const AnimationID& animationType, const std::string& previousAnimationName, const AnimationGroupID animationGroupID) { + auto& animations = GetEntriesMutable(); CDAnimationKey animationKey(animationType, animationGroupID); - auto animationEntryCached = this->animations.find(animationKey); - if (animationEntryCached == this->animations.end()) { + auto animationEntryCached = animations.find(animationKey); + if (animationEntryCached == animations.end()) { this->CacheAnimations(animationKey); } - auto animationEntry = this->animations.find(animationKey); + auto animationEntry = animations.find(animationKey); // If we have only one animation, return it regardless of the chance to play. if (animationEntry->second.size() == 1) { - return CDAnimationLookupResult(animationEntry->second.front()); + return animationEntry->second.front(); } auto randomAnimation = GeneralUtils::GenerateRandomNumber(0, 1); for (auto& animationEntry : animationEntry->second) { randomAnimation -= animationEntry.chance_to_play; // This is how the client gets the random animation. - if (animationEntry.animation_name != previousAnimationName && randomAnimation <= 0.0f) return CDAnimationLookupResult(animationEntry); + if (animationEntry.animation_name != previousAnimationName && randomAnimation <= 0.0f) return animationEntry; } - return CDAnimationLookupResult(); + return std::nullopt; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.h index 1b6280ca..643ef98f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.h @@ -2,6 +2,11 @@ #include "CDTable.h" #include +#include + +typedef int32_t AnimationGroupID; +typedef std::string AnimationID; +typedef std::pair CDAnimationKey; struct CDAnimation { // uint32_t animationGroupID; @@ -20,12 +25,7 @@ struct CDAnimation { UNUSED_COLUMN(float blendTime;) //!< The blend time }; -typedef LookupResult CDAnimationLookupResult; - -class CDAnimationsTable : public CDTable { - typedef int32_t AnimationGroupID; - typedef std::string AnimationID; - typedef std::pair CDAnimationKey; +class CDAnimationsTable : public CDTable>> { public: void LoadValuesFromDatabase(); /** @@ -38,7 +38,7 @@ public: * @param animationGroupID The animationGroupID to lookup * @return CDAnimationLookupResult */ - [[nodiscard]] CDAnimationLookupResult GetAnimation(const AnimationID& animationType, const std::string& previousAnimationName, const AnimationGroupID animationGroupID); + [[nodiscard]] std::optional GetAnimation(const AnimationID& animationType, const std::string& previousAnimationName, const AnimationGroupID animationGroupID); /** * Cache a full AnimationGroup by its ID. @@ -58,10 +58,4 @@ private: * @return false */ bool CacheData(CppSQLite3Statement& queryToCache); - - /** - * Each animation is key'd by its animationName and its animationGroupID. Each - * animation has a possible list of animations. This is because there can be animations have a percent chance to play so one is selected at random. - */ - std::map> animations; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.cpp index 708bec4c..57187c7c 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.cpp @@ -1,6 +1,10 @@ #include "CDBehaviorParameterTable.h" #include "GeneralUtils.h" +namespace { + std::unordered_map m_ParametersList; +}; + uint64_t GetKey(const uint32_t behaviorID, const uint32_t parameterID) { uint64_t key = behaviorID; key <<= 31U; @@ -11,6 +15,7 @@ uint64_t GetKey(const uint32_t behaviorID, const uint32_t parameterID) { void CDBehaviorParameterTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorParameter"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { uint32_t behaviorID = tableData.getIntField("behaviorID", -1); auto candidateStringToAdd = std::string(tableData.getStringField("parameterID", "")); @@ -24,7 +29,7 @@ void CDBehaviorParameterTable::LoadValuesFromDatabase() { uint64_t hash = GetKey(behaviorID, parameterId); float value = tableData.getFloatField("value", -1.0f); - m_Entries.insert(std::make_pair(hash, value)); + entries.insert(std::make_pair(hash, value)); tableData.nextRow(); } @@ -32,22 +37,24 @@ void CDBehaviorParameterTable::LoadValuesFromDatabase() { } float CDBehaviorParameterTable::GetValue(const uint32_t behaviorID, const std::string& name, const float defaultValue) { - auto parameterID = this->m_ParametersList.find(name); - if (parameterID == this->m_ParametersList.end()) return defaultValue; + auto parameterID = m_ParametersList.find(name); + if (parameterID == m_ParametersList.end()) return defaultValue; auto hash = GetKey(behaviorID, parameterID->second); // Search for specific parameter - auto it = m_Entries.find(hash); - return it != m_Entries.end() ? it->second : defaultValue; + auto& entries = GetEntriesMutable(); + auto it = entries.find(hash); + return it != entries.end() ? it->second : defaultValue; } std::map CDBehaviorParameterTable::GetParametersByBehaviorID(uint32_t behaviorID) { + auto& entries = GetEntriesMutable(); uint64_t hashBase = behaviorID; std::map returnInfo; for (auto& [parameterString, parameterId] : m_ParametersList) { uint64_t hash = GetKey(hashBase, parameterId); - auto infoCandidate = m_Entries.find(hash); - if (infoCandidate != m_Entries.end()) { + auto infoCandidate = entries.find(hash); + if (infoCandidate != entries.end()) { returnInfo.insert(std::make_pair(parameterString, infoCandidate->second)); } } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.h index 3daa3aa3..ba6ad6c1 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.h @@ -5,12 +5,10 @@ #include #include -class CDBehaviorParameterTable : public CDTable { -private: - typedef uint64_t BehaviorParameterHash; - typedef float BehaviorParameterValue; - std::unordered_map m_Entries; - std::unordered_map m_ParametersList; +typedef uint64_t BehaviorParameterHash; +typedef float BehaviorParameterValue; + +class CDBehaviorParameterTable : public CDTable> { public: void LoadValuesFromDatabase(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.cpp index a67398a9..983156e3 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.cpp @@ -1,5 +1,9 @@ #include "CDBehaviorTemplateTable.h" +namespace { + std::unordered_set m_EffectHandles; +}; + void CDBehaviorTemplateTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -13,11 +17,9 @@ void CDBehaviorTemplateTable::LoadValuesFromDatabase() { tableSize.finalize(); - // Reserve the size - this->entries.reserve(size); - // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorTemplate"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDBehaviorTemplate entry; entry.behaviorID = tableData.getIntField("behaviorID", -1); @@ -31,30 +33,17 @@ void CDBehaviorTemplateTable::LoadValuesFromDatabase() { entry.effectHandle = m_EffectHandles.insert(candidateToAdd).first; } - this->entries.push_back(entry); - this->entriesMappedByBehaviorID.insert(std::make_pair(entry.behaviorID, entry)); + entries.insert(std::make_pair(entry.behaviorID, entry)); tableData.nextRow(); } tableData.finalize(); } -std::vector CDBehaviorTemplateTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; -} - -const std::vector& CDBehaviorTemplateTable::GetEntries() const { - return this->entries; -} - const CDBehaviorTemplate CDBehaviorTemplateTable::GetByBehaviorID(uint32_t behaviorID) { - auto entry = this->entriesMappedByBehaviorID.find(behaviorID); - if (entry == this->entriesMappedByBehaviorID.end()) { + auto& entries = GetEntriesMutable(); + auto entry = entries.find(behaviorID); + if (entry == entries.end()) { CDBehaviorTemplate entryToReturn; entryToReturn.behaviorID = 0; entryToReturn.effectHandle = m_EffectHandles.end(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.h index cbc494a2..367f5f0a 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.h @@ -12,19 +12,9 @@ struct CDBehaviorTemplate { std::unordered_set::iterator effectHandle; //!< The effect handle }; - -class CDBehaviorTemplateTable : public CDTable { -private: - std::vector entries; - std::unordered_map entriesMappedByBehaviorID; - std::unordered_set m_EffectHandles; +class CDBehaviorTemplateTable : public CDTable> { public: void LoadValuesFromDatabase(); - // Queries the table with a custom "where" clause - std::vector Query(std::function predicate); - - const std::vector& GetEntries(void) const; - const CDBehaviorTemplate GetByBehaviorID(uint32_t behaviorID); }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.cpp index abc917b5..c2714396 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.cpp @@ -14,7 +14,8 @@ void CDBrickIDTableTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BrickIDTable"); @@ -23,7 +24,7 @@ void CDBrickIDTableTable::LoadValuesFromDatabase() { entry.NDObjectID = tableData.getIntField("NDObjectID", -1); entry.LEGOBrickID = tableData.getIntField("LEGOBrickID", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -31,15 +32,9 @@ void CDBrickIDTableTable::LoadValuesFromDatabase() { } std::vector CDBrickIDTableTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDBrickIDTableTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.h index 1a9f9a94..9a2c2523 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.h @@ -16,14 +16,9 @@ struct CDBrickIDTable { //! BrickIDTable table -class CDBrickIDTableTable : public CDTable { -private: - std::vector entries; - +class CDBrickIDTableTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.cpp index 3cf7ac62..4944c13b 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.cpp @@ -4,14 +4,15 @@ void CDComponentsRegistryTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ComponentsRegistry"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDComponentsRegistry entry; entry.id = tableData.getIntField("id", -1); entry.component_type = static_cast(tableData.getIntField("component_type", 0)); entry.component_id = tableData.getIntField("component_id", -1); - this->mappedEntries.insert_or_assign(static_cast(entry.component_type) << 32 | static_cast(entry.id), entry.component_id); - this->mappedEntries.insert_or_assign(entry.id, 0); + entries.insert_or_assign(static_cast(entry.component_type) << 32 | static_cast(entry.id), entry.component_id); + entries.insert_or_assign(entry.id, 0); tableData.nextRow(); } @@ -20,10 +21,11 @@ void CDComponentsRegistryTable::LoadValuesFromDatabase() { } int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, eReplicaComponentType componentType, int32_t defaultValue) { - auto exists = mappedEntries.find(id); - if (exists != mappedEntries.end()) { - auto iter = mappedEntries.find(static_cast(componentType) << 32 | static_cast(id)); - return iter == mappedEntries.end() ? defaultValue : iter->second; + auto& entries = GetEntriesMutable(); + auto exists = entries.find(id); + if (exists != entries.end()) { + auto iter = entries.find(static_cast(componentType) << 32 | static_cast(id)); + return iter == entries.end() ? defaultValue : iter->second; } // Now get the data. Get all components of this entity so we dont do a query for each component @@ -38,14 +40,14 @@ int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, eReplicaComponent entry.component_type = static_cast(tableData.getIntField("component_type", 0)); entry.component_id = tableData.getIntField("component_id", -1); - this->mappedEntries.insert_or_assign(static_cast(entry.component_type) << 32 | static_cast(entry.id), entry.component_id); + entries.insert_or_assign(static_cast(entry.component_type) << 32 | static_cast(entry.id), entry.component_id); tableData.nextRow(); } - mappedEntries.insert_or_assign(id, 0); + entries.insert_or_assign(id, 0); - auto iter = this->mappedEntries.find(static_cast(componentType) << 32 | static_cast(id)); + auto iter = entries.find(static_cast(componentType) << 32 | static_cast(id)); - return iter == this->mappedEntries.end() ? defaultValue : iter->second; + return iter == entries.end() ? defaultValue : iter->second; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.h index 45da7614..2165f907 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.h @@ -13,10 +13,7 @@ struct CDComponentsRegistry { }; -class CDComponentsRegistryTable : public CDTable { -private: - std::unordered_map mappedEntries; //id, component_type, component_id - +class CDComponentsRegistryTable : public CDTable> { public: void LoadValuesFromDatabase(); int32_t GetByIDAndType(uint32_t id, eReplicaComponentType componentType, int32_t defaultValue = 0); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.cpp index deb2b168..19ac7da0 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.cpp @@ -15,7 +15,8 @@ void CDCurrencyTableTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM CurrencyTable"); @@ -27,7 +28,7 @@ void CDCurrencyTableTable::LoadValuesFromDatabase() { entry.maxvalue = tableData.getIntField("maxvalue", -1); entry.id = tableData.getIntField("id", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -35,15 +36,9 @@ void CDCurrencyTableTable::LoadValuesFromDatabase() { } std::vector CDCurrencyTableTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDCurrencyTableTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.h index 9c68c277..1cd6c142 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.h @@ -18,14 +18,9 @@ struct CDCurrencyTable { }; //! CurrencyTable table -class CDCurrencyTableTable : public CDTable { -private: - std::vector entries; - +class CDCurrencyTableTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.cpp index 4939a50e..b1a6f699 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.cpp @@ -13,7 +13,8 @@ void CDDestructibleComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM DestructibleComponent"); @@ -34,7 +35,7 @@ void CDDestructibleComponentTable::LoadValuesFromDatabase() { entry.isSmashable = tableData.getIntField("isSmashable", -1) == 1 ? true : false; entry.difficultyLevel = tableData.getIntField("difficultyLevel", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -42,15 +43,9 @@ void CDDestructibleComponentTable::LoadValuesFromDatabase() { } std::vector CDDestructibleComponentTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDDestructibleComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.h index 0871d9ea..3319907b 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.h @@ -20,14 +20,9 @@ struct CDDestructibleComponent { int32_t difficultyLevel; //!< ??? }; -class CDDestructibleComponentTable : public CDTable { -private: - std::vector entries; - +class CDDestructibleComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.cpp index a7f39705..28052819 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.cpp @@ -2,6 +2,7 @@ void CDEmoteTableTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Emotes"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDEmoteTable entry; entry.ID = tableData.getIntField("id", -1); @@ -21,6 +22,7 @@ void CDEmoteTableTable::LoadValuesFromDatabase() { } CDEmoteTable* CDEmoteTableTable::GetEmote(int32_t id) { + auto& entries = GetEntriesMutable(); auto itr = entries.find(id); return itr != entries.end() ? &itr->second : nullptr; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.h index 360cfc38..ff0b28d1 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.h @@ -26,10 +26,7 @@ struct CDEmoteTable { std::string gateVersion; }; -class CDEmoteTableTable : public CDTable { -private: - std::map entries; - +class CDEmoteTableTable : public CDTable> { public: void LoadValuesFromDatabase(); // Returns an emote by ID diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.cpp index 1a146bf1..407efff7 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.cpp @@ -14,7 +14,8 @@ void CDFeatureGatingTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM FeatureGating"); @@ -26,7 +27,7 @@ void CDFeatureGatingTable::LoadValuesFromDatabase() { entry.minor = tableData.getIntField("minor", -1); entry.description = tableData.getStringField("description", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -35,7 +36,8 @@ void CDFeatureGatingTable::LoadValuesFromDatabase() { std::vector CDFeatureGatingTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + auto& entries = GetEntriesMutable(); + std::vector data = cpplinq::from(entries) >> cpplinq::where(predicate) >> cpplinq::to_vector(); @@ -43,6 +45,7 @@ std::vector CDFeatureGatingTable::Query(std::function= entry) { return true; @@ -51,8 +54,3 @@ bool CDFeatureGatingTable::FeatureUnlocked(const CDFeatureGating& feature) const return false; } - -const std::vector& CDFeatureGatingTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.h index 5df202e3..65f33395 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.h @@ -17,10 +17,7 @@ struct CDFeatureGating { } }; -class CDFeatureGatingTable : public CDTable { -private: - std::vector entries; - +class CDFeatureGatingTable : public CDTable> { public: void LoadValuesFromDatabase(); @@ -28,6 +25,4 @@ public: std::vector Query(std::function predicate); bool FeatureUnlocked(const CDFeatureGating& feature) const; - - const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.cpp index 1a21a899..8cf3d8da 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.cpp @@ -14,7 +14,8 @@ void CDInventoryComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM InventoryComponent"); @@ -25,7 +26,7 @@ void CDInventoryComponentTable::LoadValuesFromDatabase() { entry.count = tableData.getIntField("count", -1); entry.equip = tableData.getIntField("equip", -1) == 1 ? true : false; - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -33,15 +34,9 @@ void CDInventoryComponentTable::LoadValuesFromDatabase() { } std::vector CDInventoryComponentTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDInventoryComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.h index 1f5a525d..361e1a90 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.h @@ -10,14 +10,9 @@ struct CDInventoryComponent { bool equip; //!< Whether or not to equip the item }; -class CDInventoryComponentTable : public CDTable { -private: - std::vector entries; - +class CDInventoryComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.cpp index 9f7609e9..0d8b1ad9 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.cpp @@ -17,6 +17,7 @@ void CDItemComponentTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemComponent"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDItemComponent entry; entry.id = tableData.getIntField("id", -1); @@ -62,7 +63,7 @@ void CDItemComponentTable::LoadValuesFromDatabase() { entry.forgeType = tableData.getIntField("forgeType", -1); entry.SellMultiplier = tableData.getFloatField("SellMultiplier", -1.0f); - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -70,8 +71,9 @@ void CDItemComponentTable::LoadValuesFromDatabase() { } const CDItemComponent& CDItemComponentTable::GetItemComponentByID(uint32_t skillID) { - const auto& it = this->entries.find(skillID); - if (it != this->entries.end()) { + auto& entries = GetEntriesMutable(); + const auto& it = entries.find(skillID); + if (it != entries.end()) { return it->second; } @@ -129,12 +131,12 @@ const CDItemComponent& CDItemComponentTable::GetItemComponentByID(uint32_t skill entry.forgeType = tableData.getIntField("forgeType", -1); entry.SellMultiplier = tableData.getFloatField("SellMultiplier", -1.0f); - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } - const auto& it2 = this->entries.find(skillID); - if (it2 != this->entries.end()) { + const auto& it2 = entries.find(skillID); + if (it2 != entries.end()) { return it2->second; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.h index 014c9801..60a3e412 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.h @@ -49,10 +49,7 @@ struct CDItemComponent { float SellMultiplier; //!< Something to do with early vendors perhaps (but replaced) }; -class CDItemComponentTable : public CDTable { -private: - std::map entries; - +class CDItemComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); static std::map ParseCraftingCurrencies(const CDItemComponent& itemComponent); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.cpp index 0376bad4..79bd69ae 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.cpp @@ -14,7 +14,8 @@ void CDItemSetSkillsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSetSkills"); @@ -24,7 +25,7 @@ void CDItemSetSkillsTable::LoadValuesFromDatabase() { entry.SkillID = tableData.getIntField("SkillID", -1); entry.SkillCastType = tableData.getIntField("SkillCastType", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -32,22 +33,17 @@ void CDItemSetSkillsTable::LoadValuesFromDatabase() { } std::vector CDItemSetSkillsTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } -const std::vector& CDItemSetSkillsTable::GetEntries() const { - return this->entries; -} - std::vector CDItemSetSkillsTable::GetBySkillID(uint32_t SkillSetID) { std::vector toReturn; - for (CDItemSetSkills entry : this->entries) { + for (const auto& entry : GetEntries()) { if (entry.SkillSetID == SkillSetID) toReturn.push_back(entry); if (entry.SkillSetID > SkillSetID) return toReturn; //stop seeking in the db if it's not needed. } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.h index ee5fda05..78e708ae 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.h @@ -9,16 +9,11 @@ struct CDItemSetSkills { uint32_t SkillCastType; //!< The skill cast type }; -class CDItemSetSkillsTable : public CDTable { -private: - std::vector entries; - +class CDItemSetSkillsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - const std::vector& GetEntries() const; - std::vector GetBySkillID(uint32_t SkillSetID); }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.cpp index f3859ae2..77b3b1e7 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.cpp @@ -14,7 +14,8 @@ void CDItemSetsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSets"); @@ -36,7 +37,7 @@ void CDItemSetsTable::LoadValuesFromDatabase() { entry.kitID = tableData.getIntField("kitID", -1); entry.priority = tableData.getFloatField("priority", -1.0f); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -45,14 +46,9 @@ void CDItemSetsTable::LoadValuesFromDatabase() { std::vector CDItemSetsTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDItemSetsTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.h index 77cc0c35..45b91590 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.h @@ -21,15 +21,10 @@ struct CDItemSets { float priority; //!< The priority }; -class CDItemSetsTable : public CDTable { -private: - std::vector entries; - +class CDItemSetsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.cpp index 930f3a85..284cf484 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.cpp @@ -14,7 +14,8 @@ void CDLevelProgressionLookupTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LevelProgressionLookup"); @@ -24,7 +25,7 @@ void CDLevelProgressionLookupTable::LoadValuesFromDatabase() { entry.requiredUScore = tableData.getIntField("requiredUScore", -1); entry.BehaviorEffect = tableData.getStringField("BehaviorEffect", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -33,14 +34,9 @@ void CDLevelProgressionLookupTable::LoadValuesFromDatabase() { std::vector CDLevelProgressionLookupTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDLevelProgressionLookupTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.h index fa1bb4cc..050d910e 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.h @@ -9,15 +9,10 @@ struct CDLevelProgressionLookup { std::string BehaviorEffect; //!< The behavior effect attached to this }; -class CDLevelProgressionLookupTable : public CDTable { -private: - std::vector entries; - +class CDLevelProgressionLookupTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.cpp index 36bebb69..cd8ae5c4 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.cpp @@ -25,7 +25,8 @@ void CDLootMatrixTable::LoadValuesFromDatabase() { } // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootMatrix"); @@ -33,14 +34,15 @@ void CDLootMatrixTable::LoadValuesFromDatabase() { CDLootMatrix entry; uint32_t lootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); - this->entries[lootMatrixIndex].push_back(ReadRow(tableData)); + entries[lootMatrixIndex].push_back(ReadRow(tableData)); tableData.nextRow(); } } const LootMatrixEntries& CDLootMatrixTable::GetMatrix(uint32_t matrixId) { - auto itr = this->entries.find(matrixId); - if (itr != this->entries.end()) { + auto& entries = GetEntriesMutable(); + auto itr = entries.find(matrixId); + if (itr != entries.end()) { return itr->second; } @@ -49,10 +51,10 @@ const LootMatrixEntries& CDLootMatrixTable::GetMatrix(uint32_t matrixId) { auto tableData = query.execQuery(); while (!tableData.eof()) { - this->entries[matrixId].push_back(ReadRow(tableData)); + entries[matrixId].push_back(ReadRow(tableData)); tableData.nextRow(); } - return this->entries[matrixId]; + return entries[matrixId]; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.h index c7157e07..b0ce7e0f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.h @@ -16,7 +16,7 @@ struct CDLootMatrix { typedef uint32_t LootMatrixIndex; typedef std::vector LootMatrixEntries; -class CDLootMatrixTable : public CDTable { +class CDLootMatrixTable : public CDTable> { public: void LoadValuesFromDatabase(); @@ -24,6 +24,5 @@ public: const LootMatrixEntries& GetMatrix(uint32_t matrixId); private: CDLootMatrix ReadRow(CppSQLite3Query& tableData) const; - std::unordered_map entries; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp index 7d04db13..d5e9d4dc 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp @@ -49,7 +49,8 @@ void CDLootTableTable::LoadValuesFromDatabase() { } // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootTable"); @@ -57,17 +58,18 @@ void CDLootTableTable::LoadValuesFromDatabase() { CDLootTable entry; uint32_t lootTableIndex = tableData.getIntField("LootTableIndex", -1); - this->entries[lootTableIndex].push_back(ReadRow(tableData)); + entries[lootTableIndex].push_back(ReadRow(tableData)); tableData.nextRow(); } - for (auto& [id, table] : this->entries) { + for (auto& [id, table] : entries) { SortTable(table); } } const LootTableEntries& CDLootTableTable::GetTable(uint32_t tableId) { - auto itr = this->entries.find(tableId); - if (itr != this->entries.end()) { + auto& entries = GetEntriesMutable(); + auto itr = entries.find(tableId); + if (itr != entries.end()) { return itr->second; } @@ -77,10 +79,10 @@ const LootTableEntries& CDLootTableTable::GetTable(uint32_t tableId) { while (!tableData.eof()) { CDLootTable entry; - this->entries[tableId].push_back(ReadRow(tableData)); + entries[tableId].push_back(ReadRow(tableData)); tableData.nextRow(); } - SortTable(this->entries[tableId]); + SortTable(entries[tableId]); - return this->entries[tableId]; + return entries[tableId]; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.h index e432d621..416bd87a 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.h @@ -13,10 +13,9 @@ struct CDLootTable { typedef uint32_t LootTableIndex; typedef std::vector LootTableEntries; -class CDLootTableTable : public CDTable { +class CDLootTableTable : public CDTable> { private: CDLootTable ReadRow(CppSQLite3Query& tableData) const; - std::unordered_map entries; public: void LoadValuesFromDatabase(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.cpp index c7e884c2..1123bfec 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.cpp @@ -1,7 +1,7 @@ #include "CDMissionEmailTable.h" -void CDMissionEmailTable::LoadValuesFromDatabase() { +void CDMissionEmailTable::LoadValuesFromDatabase() { // First, get the size of the table uint32_t size = 0; auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM MissionEmail"); @@ -14,7 +14,8 @@ void CDMissionEmailTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionEmail"); @@ -29,7 +30,7 @@ void CDMissionEmailTable::LoadValuesFromDatabase() { entry.locStatus = tableData.getIntField("locStatus", -1); entry.gate_version = tableData.getStringField("gate_version", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -38,15 +39,9 @@ void CDMissionEmailTable::LoadValuesFromDatabase() { //! Queries the table with a custom "where" clause std::vector CDMissionEmailTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -//! Gets all the entries in the table -const std::vector& CDMissionEmailTable::GetEntries() const { - return this->entries; -} diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.h index 06c15e71..ac2dba81 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.h @@ -15,14 +15,9 @@ struct CDMissionEmail { }; -class CDMissionEmailTable : public CDTable { -private: - std::vector entries; - +class CDMissionEmailTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.cpp index 87d2bd61..efe284d4 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.cpp @@ -14,7 +14,8 @@ void CDMissionNPCComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionNPCComponent"); @@ -26,7 +27,7 @@ void CDMissionNPCComponentTable::LoadValuesFromDatabase() { entry.acceptsMission = tableData.getIntField("acceptsMission", -1) == 1 ? true : false; entry.gate_version = tableData.getStringField("gate_version", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -36,15 +37,9 @@ void CDMissionNPCComponentTable::LoadValuesFromDatabase() { //! Queries the table with a custom "where" clause std::vector CDMissionNPCComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -//! Gets all the entries in the table -const std::vector& CDMissionNPCComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.h index 8c4b790d..1eba2fad 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.h @@ -11,17 +11,10 @@ struct CDMissionNPCComponent { std::string gate_version; //!< The gate version }; -class CDMissionNPCComponentTable : public CDTable { -private: - std::vector entries; - +class CDMissionNPCComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - // Gets all the entries in the table - const std::vector& GetEntries() const; - }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.cpp index b2cb9e21..c5b6620f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.cpp @@ -14,7 +14,8 @@ void CDMissionTasksTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionTasks"); @@ -34,7 +35,7 @@ void CDMissionTasksTable::LoadValuesFromDatabase() { UNUSED(entry.localize = tableData.getIntField("localize", -1) == 1 ? true : false); UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -43,7 +44,7 @@ void CDMissionTasksTable::LoadValuesFromDatabase() { std::vector CDMissionTasksTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); @@ -53,7 +54,8 @@ std::vector CDMissionTasksTable::Query(std::function CDMissionTasksTable::GetByMissionID(uint32_t missionID) { std::vector tasks; - for (auto& entry : this->entries) { + // TODO: this should not be linear(?) and also shouldnt need to be a pointer + for (auto& entry : GetEntriesMutable()) { if (entry.id == missionID) { tasks.push_back(&entry); } @@ -62,7 +64,6 @@ std::vector CDMissionTasksTable::GetByMissionID(uint32_t missio return tasks; } -const std::vector& CDMissionTasksTable::GetEntries() const { - return this->entries; +const typename CDMissionTasksTable::StorageType& CDMissionTasksTable::GetEntries() const { + return CDTable::GetEntries(); } - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.h index 420dbfbe..97553359 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.h @@ -19,10 +19,7 @@ struct CDMissionTasks { UNUSED(std::string gate_version); //!< ??? }; -class CDMissionTasksTable : public CDTable { -private: - std::vector entries; - +class CDMissionTasksTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause @@ -30,6 +27,7 @@ public: std::vector GetByMissionID(uint32_t missionID); - const std::vector& GetEntries() const; + // TODO: Remove this and replace it with a proper lookup function. + const CDTable::StorageType& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp index bc9eb76c..8862b1db 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp @@ -16,7 +16,8 @@ void CDMissionsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Missions"); @@ -75,7 +76,7 @@ void CDMissionsTable::LoadValuesFromDatabase() { UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1)); entry.reward_bankinventory = tableData.getIntField("reward_bankinventory", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -86,19 +87,15 @@ void CDMissionsTable::LoadValuesFromDatabase() { std::vector CDMissionsTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } -const std::vector& CDMissionsTable::GetEntries(void) const { - return this->entries; -} - const CDMissions* CDMissionsTable::GetPtrByMissionID(uint32_t missionID) const { - for (const auto& entry : entries) { + for (const auto& entry : GetEntries()) { if (entry.id == missionID) { return const_cast(&entry); } @@ -108,7 +105,7 @@ const CDMissions* CDMissionsTable::GetPtrByMissionID(uint32_t missionID) const { } const CDMissions& CDMissionsTable::GetByMissionID(uint32_t missionID, bool& found) const { - for (const auto& entry : entries) { + for (const auto& entry : GetEntries()) { if (entry.id == missionID) { found = true; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h index de4b21c3..6ba7b19e 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h @@ -60,18 +60,12 @@ struct CDMissions { int32_t reward_bankinventory; //!< The amount of bank space this mission rewards }; -class CDMissionsTable : public CDTable { -private: - std::vector entries; - +class CDMissionsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - // Gets all the entries in the table - const std::vector& GetEntries() const; - const CDMissions* GetPtrByMissionID(uint32_t missionID) const; const CDMissions& GetByMissionID(uint32_t missionID, bool& found) const; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.cpp index be1c3d96..48964a59 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.cpp @@ -14,7 +14,8 @@ void CDMovementAIComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MovementAIComponent"); @@ -29,7 +30,7 @@ void CDMovementAIComponentTable::LoadValuesFromDatabase() { entry.WanderRadius = tableData.getFloatField("WanderRadius", -1.0f); entry.attachedPath = tableData.getStringField("attachedPath", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -38,14 +39,9 @@ void CDMovementAIComponentTable::LoadValuesFromDatabase() { std::vector CDMovementAIComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDMovementAIComponentTable::GetEntries(void) const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.h index 8b415f3a..34d01e3d 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.h @@ -14,15 +14,9 @@ struct CDMovementAIComponent { std::string attachedPath; }; -class CDMovementAIComponentTable : public CDTable { -private: - std::vector entries; - +class CDMovementAIComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - // Gets all the entries in the table - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.cpp index 958c6cc8..9933fe7f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.cpp @@ -14,7 +14,8 @@ void CDObjectSkillsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ObjectSkills"); @@ -25,7 +26,7 @@ void CDObjectSkillsTable::LoadValuesFromDatabase() { entry.castOnType = tableData.getIntField("castOnType", -1); entry.AICombatWeight = tableData.getIntField("AICombatWeight", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -34,13 +35,9 @@ void CDObjectSkillsTable::LoadValuesFromDatabase() { std::vector CDObjectSkillsTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDObjectSkillsTable::GetEntries() const { - return this->entries; -} diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.h index 0b88fb6f..a2a8d440 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.h @@ -10,17 +10,10 @@ struct CDObjectSkills { uint32_t AICombatWeight; //!< ??? }; -class CDObjectSkillsTable : public CDTable { -private: - std::vector entries; - +class CDObjectSkillsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - // Gets all the entries in the table - const std::vector& GetEntries() const; - }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.cpp index 3282e14c..d1f6771e 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.cpp @@ -1,5 +1,9 @@ #include "CDObjectsTable.h" +namespace { + CDObjects m_default; +}; + void CDObjectsTable::LoadValuesFromDatabase() { // First, get the size of the table uint32_t size = 0; @@ -14,6 +18,7 @@ void CDObjectsTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Objects"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDObjects entry; entry.id = tableData.getIntField("id", -1); @@ -31,7 +36,7 @@ void CDObjectsTable::LoadValuesFromDatabase() { UNUSED_COLUMN(entry.gate_version = tableData.getStringField("gate_version", "");) UNUSED_COLUMN(entry.HQ_valid = tableData.getIntField("HQ_valid", -1);) - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -41,8 +46,9 @@ void CDObjectsTable::LoadValuesFromDatabase() { } const CDObjects& CDObjectsTable::GetByID(uint32_t LOT) { - const auto& it = this->entries.find(LOT); - if (it != this->entries.end()) { + auto& entries = GetEntriesMutable(); + const auto& it = entries.find(LOT); + if (it != entries.end()) { return it->second; } @@ -51,7 +57,7 @@ const CDObjects& CDObjectsTable::GetByID(uint32_t LOT) { auto tableData = query.execQuery(); if (tableData.eof()) { - this->entries.insert(std::make_pair(LOT, m_default)); + entries.insert(std::make_pair(LOT, m_default)); return m_default; } @@ -73,7 +79,7 @@ const CDObjects& CDObjectsTable::GetByID(uint32_t LOT) { UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); UNUSED(entry.HQ_valid = tableData.getIntField("HQ_valid", -1)); - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.h index 2ef47727..add21c8f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.h @@ -20,11 +20,7 @@ struct CDObjects { UNUSED(uint32_t HQ_valid); //!< Probably used for the Nexus HQ database on LEGOUniverse.com }; -class CDObjectsTable : public CDTable { -private: - std::map entries; - CDObjects m_default; - +class CDObjectsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Gets an entry by ID diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.cpp index 8038c779..da100026 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.cpp @@ -13,8 +13,8 @@ void CDPackageComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); - // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PackageComponent"); @@ -24,7 +24,7 @@ void CDPackageComponentTable::LoadValuesFromDatabase() { entry.LootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); entry.packageType = tableData.getIntField("packageType", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -34,15 +34,9 @@ void CDPackageComponentTable::LoadValuesFromDatabase() { //! Queries the table with a custom "where" clause std::vector CDPackageComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -//! Gets all the entries in the table -const std::vector& CDPackageComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.h index cc8b0636..ad7003df 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.h @@ -9,14 +9,9 @@ struct CDPackageComponent { uint32_t packageType; }; -class CDPackageComponentTable : public CDTable { -private: - std::vector entries; - +class CDPackageComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp index c3dd5d50..f3371ecb 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp @@ -23,10 +23,12 @@ namespace { void CDPetComponentTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PetComponent"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { const uint32_t componentID = tableData.getIntField("id", defaultEntry.id); - auto& entry = m_Entries[componentID]; + auto& entry = entries[componentID]; + entry.id = componentID; UNUSED_COLUMN(entry.minTameUpdateTime = tableData.getFloatField("minTameUpdateTime", defaultEntry.minTameUpdateTime)); UNUSED_COLUMN(entry.maxTameUpdateTime = tableData.getFloatField("maxTameUpdateTime", defaultEntry.maxTameUpdateTime)); @@ -48,12 +50,13 @@ void CDPetComponentTable::LoadValuesFromDatabase() { } void CDPetComponentTable::LoadValuesFromDefaults() { - m_Entries.insert(std::make_pair(defaultEntry.id, defaultEntry)); + GetEntriesMutable().insert(std::make_pair(defaultEntry.id, defaultEntry)); } CDPetComponent& CDPetComponentTable::GetByID(const uint32_t componentID) { - auto itr = m_Entries.find(componentID); - if (itr == m_Entries.end()) { + auto& entries = GetEntriesMutable(); + auto itr = entries.find(componentID); + if (itr == entries.end()) { LOG("Unable to load pet component (ID %i) values from database! Using default values instead.", componentID); return defaultEntry; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.h index fa54e457..42890253 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.h @@ -21,7 +21,7 @@ struct CDPetComponent { UNUSED_COLUMN(std::string buffIDs;) }; -class CDPetComponentTable : public CDTable { +class CDPetComponentTable : public CDTable> { public: /** @@ -39,7 +39,4 @@ public: * @returns A reference to the corresponding table, or the default if one could not be found */ CDPetComponent& GetByID(const uint32_t componentID); - -private: - std::map m_Entries; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.cpp index ebc5327b..34671f3c 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.cpp @@ -2,6 +2,7 @@ void CDPhysicsComponentTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PhysicsComponent"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDPhysicsComponent entry; entry.id = tableData.getIntField("id", -1); @@ -21,7 +22,7 @@ void CDPhysicsComponentTable::LoadValuesFromDatabase() { UNUSED(entry->friction = tableData.getFloatField("friction")); UNUSED(entry->gravityVolumeAsset = tableData.getStringField("gravityVolumeAsset")); - m_entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -29,7 +30,8 @@ void CDPhysicsComponentTable::LoadValuesFromDatabase() { } CDPhysicsComponent* CDPhysicsComponentTable::GetByID(uint32_t componentID) { - auto itr = m_entries.find(componentID); - return itr != m_entries.end() ? &itr->second : nullptr; + auto& entries = GetEntriesMutable(); + auto itr = entries.find(componentID); + return itr != entries.end() ? &itr->second : nullptr; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.h index 5ed33cc9..f0a62139 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.h @@ -21,13 +21,10 @@ struct CDPhysicsComponent { UNUSED(std::string gravityVolumeAsset); }; -class CDPhysicsComponentTable : public CDTable { +class CDPhysicsComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); static const std::string GetTableName() { return "PhysicsComponent"; }; CDPhysicsComponent* GetByID(uint32_t componentID); - -private: - std::map m_entries; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.cpp index c1532c86..dfb591d1 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.cpp @@ -1,5 +1,9 @@ #include "CDPropertyEntranceComponentTable.h" +namespace { + CDPropertyEntranceComponent defaultEntry{}; +}; + void CDPropertyEntranceComponentTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -12,7 +16,8 @@ void CDPropertyEntranceComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyEntranceComponent;"); while (!tableData.eof()) { @@ -24,7 +29,7 @@ void CDPropertyEntranceComponentTable::LoadValuesFromDatabase() { tableData.getStringField("groupType", "") }; - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -32,11 +37,10 @@ void CDPropertyEntranceComponentTable::LoadValuesFromDatabase() { } CDPropertyEntranceComponent CDPropertyEntranceComponentTable::GetByID(uint32_t id) { - for (const auto& entry : entries) { + for (const auto& entry : GetEntries()) { if (entry.id == id) return entry; } return defaultEntry; } - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.h index 5c7d0965..f687b881 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.h @@ -9,15 +9,9 @@ struct CDPropertyEntranceComponent { std::string groupType; }; -class CDPropertyEntranceComponentTable : public CDTable { +class CDPropertyEntranceComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause CDPropertyEntranceComponent GetByID(uint32_t id); - - // Gets all the entries in the table - [[nodiscard]] const std::vector& GetEntries() const { return entries; } -private: - std::vector entries{}; - CDPropertyEntranceComponent defaultEntry{}; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.cpp index 4a1d666e..4046b6fa 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.cpp @@ -1,5 +1,9 @@ #include "CDPropertyTemplateTable.h" +namespace { + CDPropertyTemplate defaultEntry{}; +}; + void CDPropertyTemplateTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -12,7 +16,8 @@ void CDPropertyTemplateTable::LoadValuesFromDatabase() { tableSize.finalize(); - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyTemplate;"); while (!tableData.eof()) { @@ -23,7 +28,7 @@ void CDPropertyTemplateTable::LoadValuesFromDatabase() { tableData.getStringField("spawnName", "") }; - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -31,7 +36,7 @@ void CDPropertyTemplateTable::LoadValuesFromDatabase() { } CDPropertyTemplate CDPropertyTemplateTable::GetByMapID(uint32_t mapID) { - for (const auto& entry : entries) { + for (const auto& entry : GetEntries()) { if (entry.mapID == mapID) return entry; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.h index 7261bdf9..e0c6c485 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.h @@ -8,13 +8,9 @@ struct CDPropertyTemplate { std::string spawnName; }; -class CDPropertyTemplateTable : public CDTable { +class CDPropertyTemplateTable : public CDTable> { public: void LoadValuesFromDatabase(); - static const std::string GetTableName() { return "PropertyTemplate"; }; CDPropertyTemplate GetByMapID(uint32_t mapID); -private: - std::vector entries{}; - CDPropertyTemplate defaultEntry{}; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.cpp index 6edd00b2..279d6408 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.cpp @@ -14,7 +14,8 @@ void CDProximityMonitorComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ProximityMonitorComponent"); @@ -25,7 +26,7 @@ void CDProximityMonitorComponentTable::LoadValuesFromDatabase() { entry.LoadOnClient = tableData.getIntField("LoadOnClient", -1); entry.LoadOnServer = tableData.getIntField("LoadOnServer", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -34,14 +35,9 @@ void CDProximityMonitorComponentTable::LoadValuesFromDatabase() { std::vector CDProximityMonitorComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDProximityMonitorComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.h index 861c900e..af2c385e 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.h @@ -10,14 +10,9 @@ struct CDProximityMonitorComponent { bool LoadOnServer; }; -class CDProximityMonitorComponentTable : public CDTable { -private: - std::vector entries; - +class CDProximityMonitorComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); //! Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.cpp index 34ec5826..72a26beb 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.cpp @@ -3,6 +3,7 @@ void CDRailActivatorComponentTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RailActivatorComponent;"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDRailActivatorComponent entry; @@ -36,7 +37,7 @@ void CDRailActivatorComponentTable::LoadValuesFromDatabase() { entry.showNameBillboard = tableData.getIntField("ShowNameBillboard", 0); - m_Entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -44,7 +45,7 @@ void CDRailActivatorComponentTable::LoadValuesFromDatabase() { } CDRailActivatorComponent CDRailActivatorComponentTable::GetEntryByID(int32_t id) const { - for (const auto& entry : m_Entries) { + for (const auto& entry : GetEntries()) { if (entry.id == id) return entry; } @@ -52,10 +53,6 @@ CDRailActivatorComponent CDRailActivatorComponentTable::GetEntryByID(int32_t id) return {}; } -const std::vector& CDRailActivatorComponentTable::GetEntries() const { - return m_Entries; -} - std::pair CDRailActivatorComponentTable::EffectPairFromString(std::string& str) { const auto split = GeneralUtils::SplitString(str, ':'); if (split.size() == 2) { diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.h b/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.h index d06b2d36..d9a94d37 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.h @@ -20,13 +20,10 @@ struct CDRailActivatorComponent { bool showNameBillboard; }; -class CDRailActivatorComponentTable : public CDTable { +class CDRailActivatorComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); - static const std::string GetTableName() { return "RailActivatorComponent"; }; [[nodiscard]] CDRailActivatorComponent GetEntryByID(int32_t id) const; - [[nodiscard]] const std::vector& GetEntries() const; private: static std::pair EffectPairFromString(std::string& str); - std::vector m_Entries{}; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.cpp index 6f086e34..def27339 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.cpp @@ -14,7 +14,8 @@ void CDRarityTableTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RarityTable order by randmax desc;"); @@ -30,5 +31,5 @@ void CDRarityTableTable::LoadValuesFromDatabase() { } const std::vector& CDRarityTableTable::GetRarityTable(uint32_t id) { - return entries[id]; + return GetEntriesMutable()[id]; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.h index 1248350b..006ac986 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.h @@ -6,15 +6,13 @@ struct CDRarityTable { float randmax; uint32_t rarity; + + typedef uint32_t Index; }; typedef std::vector RarityTable; -class CDRarityTableTable : public CDTable { -private: - typedef uint32_t RarityTableIndex; - std::unordered_map> entries; - +class CDRarityTableTable : public CDTable>> { public: void LoadValuesFromDatabase(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.cpp index 30534936..8a07db88 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.cpp @@ -14,7 +14,8 @@ void CDRebuildComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RebuildComponent"); @@ -31,7 +32,7 @@ void CDRebuildComponentTable::LoadValuesFromDatabase() { entry.post_imagination_cost = tableData.getIntField("post_imagination_cost", -1); entry.time_before_smash = tableData.getFloatField("time_before_smash", -1.0f); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -40,14 +41,9 @@ void CDRebuildComponentTable::LoadValuesFromDatabase() { std::vector CDRebuildComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDRebuildComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.h index aed71905..0eeb62ae 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.h @@ -16,15 +16,10 @@ struct CDRebuildComponent { float time_before_smash; //!< The time before smash }; -class CDRebuildComponentTable : public CDTable { -private: - std::vector entries; - +class CDRebuildComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.cpp index 4dab9ee9..8ade60a9 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.cpp @@ -14,7 +14,8 @@ void CDRewardCodesTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RewardCodes"); @@ -26,20 +27,20 @@ void CDRewardCodesTable::LoadValuesFromDatabase() { UNUSED_COLUMN(entry.locStatus = tableData.getIntField("locStatus", -1)); UNUSED_COLUMN(entry.gate_version = tableData.getStringField("gate_version", "")); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } } LOT CDRewardCodesTable::GetAttachmentLOT(uint32_t rewardCodeId) const { - for (auto const &entry : this->entries){ + for (auto const &entry : GetEntries()){ if (rewardCodeId == entry.id) return entry.attachmentLOT; } return LOT_NULL; } uint32_t CDRewardCodesTable::GetCodeID(std::string code) const { - for (auto const &entry : this->entries){ + for (auto const &entry : GetEntries()){ if (code == entry.code) return entry.id; } return -1; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.h index 1010a572..aa64c3bb 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.h @@ -13,13 +13,9 @@ struct CDRewardCode { }; -class CDRewardCodesTable : public CDTable { -private: - std::vector entries; - +class CDRewardCodesTable : public CDTable> { public: void LoadValuesFromDatabase(); - const std::vector& GetEntries() const; LOT GetAttachmentLOT(uint32_t rewardCodeId) const; uint32_t GetCodeID(std::string code) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.cpp index 27c2344a..4539e417 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.cpp @@ -2,6 +2,7 @@ void CDRewardsTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Rewards"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDRewards entry; entry.id = tableData.getIntField("id", -1); @@ -11,7 +12,7 @@ void CDRewardsTable::LoadValuesFromDatabase() { entry.value = tableData.getIntField("value", -1); entry.count = tableData.getIntField("count", -1); - m_entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -20,7 +21,7 @@ void CDRewardsTable::LoadValuesFromDatabase() { std::vector CDRewardsTable::GetByLevelID(uint32_t levelID) { std::vector result{}; - for (const auto& e : m_entries) { + for (const auto& e : GetEntries()) { if (e.second.levelID == levelID) result.push_back(e.second); } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.h index 9c24397b..cec787cf 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.h @@ -11,13 +11,9 @@ struct CDRewards { int32_t count; }; -class CDRewardsTable : public CDTable { +class CDRewardsTable : public CDTable> { public: void LoadValuesFromDatabase(); - static const std::string GetTableName() { return "Rewards"; }; std::vector GetByLevelID(uint32_t levelID); - -private: - std::map m_entries; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.cpp index a2fe0514..02e3e29c 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.cpp @@ -1,5 +1,9 @@ #include "CDScriptComponentTable.h" +namespace { + CDScriptComponent m_ToReturnWhenNoneFound; +}; + void CDScriptComponentTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -15,13 +19,14 @@ void CDScriptComponentTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ScriptComponent"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDScriptComponent entry; entry.id = tableData.getIntField("id", -1); entry.script_name = tableData.getStringField("script_name", ""); entry.client_script_name = tableData.getStringField("client_script_name", ""); - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -29,8 +34,9 @@ void CDScriptComponentTable::LoadValuesFromDatabase() { } const CDScriptComponent& CDScriptComponentTable::GetByID(uint32_t id) { - std::map::iterator it = this->entries.find(id); - if (it != this->entries.end()) { + auto& entries = GetEntries(); + auto it = entries.find(id); + if (it != entries.end()) { return it->second; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.h index 56296776..96c1b5a5 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.h @@ -9,11 +9,7 @@ struct CDScriptComponent { std::string client_script_name; //!< The client script name }; -class CDScriptComponentTable : public CDTable { -private: - std::map entries; - CDScriptComponent m_ToReturnWhenNoneFound; - +class CDScriptComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Gets an entry by scriptID diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.cpp index 51ed7de3..0df67884 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.cpp @@ -1,8 +1,10 @@ #include "CDSkillBehaviorTable.h" -void CDSkillBehaviorTable::LoadValuesFromDatabase() { - m_empty = CDSkillBehavior(); +namespace { + CDSkillBehavior m_empty = CDSkillBehavior(); +}; +void CDSkillBehaviorTable::LoadValuesFromDatabase() { // First, get the size of the table uint32_t size = 0; auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM SkillBehavior"); @@ -14,8 +16,7 @@ void CDSkillBehaviorTable::LoadValuesFromDatabase() { tableSize.finalize(); - // Reserve the size - //this->entries.reserve(size); + auto& entries = GetEntriesMutable(); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM SkillBehavior"); @@ -41,7 +42,7 @@ void CDSkillBehaviorTable::LoadValuesFromDatabase() { UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); UNUSED(entry.cancelType = tableData.getIntField("cancelType", -1)); - this->entries.insert(std::make_pair(entry.skillID, entry)); + entries.insert(std::make_pair(entry.skillID, entry)); //this->entries.push_back(entry); tableData.nextRow(); } @@ -50,8 +51,9 @@ void CDSkillBehaviorTable::LoadValuesFromDatabase() { } const CDSkillBehavior& CDSkillBehaviorTable::GetSkillByID(uint32_t skillID) { - std::map::iterator it = this->entries.find(skillID); - if (it != this->entries.end()) { + auto& entries = GetEntries(); + auto it = entries.find(skillID); + if (it != entries.end()) { return it->second; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.h index 0c970be6..19225d19 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.h @@ -25,11 +25,7 @@ struct CDSkillBehavior { UNUSED(uint32_t cancelType); //!< The cancel type (?) }; -class CDSkillBehaviorTable : public CDTable { -private: - std::map entries; - CDSkillBehavior m_empty; - +class CDSkillBehaviorTable : public CDTable> { public: void LoadValuesFromDatabase(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDTable.h index ab965127..4e896dbb 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDTable.h @@ -1,6 +1,7 @@ #pragma once #include "CDClientDatabase.h" +#include "CDClientManager.h" #include "Singleton.h" #include "DluAssert.h" @@ -27,22 +28,23 @@ #define UNUSED_ENTRY(v, x) #pragma warning (disable : 4244) //Disable double to float conversion warnings -#pragma warning (disable : 4715) //Disable "not all control paths return a value" +// #pragma warning (disable : 4715) //Disable "not all control paths return a value" -template +template class CDTable : public Singleton
{ +public: + typedef Storage StorageType; + protected: virtual ~CDTable() = default; -}; -template -class LookupResult { - typedef std::pair DataType; -public: - LookupResult() { m_data.first = T(); m_data.second = false; }; - LookupResult(T& data) { m_data.first = data; m_data.second = true; }; - inline const T& Data() { return m_data.first; }; - inline const bool& FoundData() { return m_data.second; }; -private: - DataType m_data; + // If you need these for a specific table, override it such that there is a public variant. + [[nodiscard]] StorageType& GetEntriesMutable() const { + return CDClientManager::GetEntriesMutable
(); + } + + // If you need these for a specific table, override it such that there is a public variant. + [[nodiscard]] const StorageType& GetEntries() const { + return GetEntriesMutable(); + } }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.cpp index 990d0b32..f639a7e3 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.cpp @@ -14,7 +14,8 @@ void CDVendorComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM VendorComponent"); @@ -26,7 +27,7 @@ void CDVendorComponentTable::LoadValuesFromDatabase() { entry.refreshTimeSeconds = tableData.getFloatField("refreshTimeSeconds", -1.0f); entry.LootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -36,15 +37,9 @@ void CDVendorComponentTable::LoadValuesFromDatabase() { //! Queries the table with a custom "where" clause std::vector CDVendorComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -//! Gets all the entries in the table -const std::vector& CDVendorComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.h index 133ce78f..cbed2d13 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.h @@ -11,15 +11,10 @@ struct CDVendorComponent { uint32_t LootMatrixIndex; //!< LootMatrixIndex of the vendor's items }; -class CDVendorComponentTable : public CDTable { -private: - std::vector entries; - +class CDVendorComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.cpp index b599c37f..6aaeb854 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.cpp @@ -15,6 +15,7 @@ void CDZoneTableTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ZoneTable"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDZoneTable entry; entry.zoneID = tableData.getIntField("zoneID", -1); @@ -45,7 +46,7 @@ void CDZoneTableTable::LoadValuesFromDatabase() { UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); entry.mountsAllowed = tableData.getIntField("mountsAllowed", -1) == 1 ? true : false; - this->m_Entries.insert(std::make_pair(entry.zoneID, entry)); + entries.insert(std::make_pair(entry.zoneID, entry)); tableData.nextRow(); } @@ -54,6 +55,7 @@ void CDZoneTableTable::LoadValuesFromDatabase() { //! Queries the table with a zoneID to find. const CDZoneTable* CDZoneTableTable::Query(uint32_t zoneID) { + auto& m_Entries = GetEntries(); const auto& iter = m_Entries.find(zoneID); if (iter != m_Entries.end()) { diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.h index 5f5970ae..b1e8b1ba 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.h @@ -33,10 +33,7 @@ struct CDZoneTable { bool mountsAllowed; //!< Whether or not mounts are allowed }; -class CDZoneTableTable : public CDTable { -private: - std::map m_Entries; - +class CDZoneTableTable : public CDTable> { public: void LoadValuesFromDatabase(); diff --git a/dGame/dComponents/RenderComponent.cpp b/dGame/dComponents/RenderComponent.cpp index d5866917..d3c74f78 100644 --- a/dGame/dComponents/RenderComponent.cpp +++ b/dGame/dComponents/RenderComponent.cpp @@ -168,10 +168,9 @@ float RenderComponent::DoAnimation(Entity* self, const std::string& animation, b auto* animationsTable = CDClientManager::GetTable(); for (auto& groupId : renderComponent->m_animationGroupIds) { auto animationGroup = animationsTable->GetAnimation(animation, renderComponent->GetLastAnimationName(), groupId); - if (animationGroup.FoundData()) { - auto data = animationGroup.Data(); - renderComponent->SetLastAnimationName(data.animation_name); - returnlength = data.animation_length; + if (animationGroup) { + renderComponent->SetLastAnimationName(animationGroup->animation_name); + returnlength = animationGroup->animation_length; } } if (sendAnimation) GameMessages::SendPlayAnimation(self, GeneralUtils::ASCIIToUTF16(animation), priority, scale); From 62b670d283cf078d42b04f391d49b1c6c30f8e30 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 9 Feb 2024 07:15:28 -0800 Subject: [PATCH 14/50] remove sha512, move md5 to thirdparty (#1443) title. Tested that Auth runs and I can login still. --- CMakeLists.txt | 3 +- dCommon/CMakeLists.txt | 7 -- dCommon/SHA512.cpp | 154 ---------------------------- dCommon/SHA512.h | 68 ------------ dNet/AuthPackets.cpp | 1 - thirdparty/CMakeLists.txt | 2 + thirdparty/MD5/CMakeLists.txt | 6 ++ {dCommon => thirdparty/MD5}/MD5.cpp | 0 {dCommon => thirdparty/MD5}/MD5.h | 0 9 files changed, 10 insertions(+), 231 deletions(-) delete mode 100644 dCommon/SHA512.cpp delete mode 100644 dCommon/SHA512.h create mode 100644 thirdparty/MD5/CMakeLists.txt rename {dCommon => thirdparty/MD5}/MD5.cpp (100%) rename {dCommon => thirdparty/MD5}/MD5.h (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1b6a775e..e085bfe7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -245,6 +245,7 @@ set(INCLUDED_DIRECTORIES "thirdparty/SQLite" "thirdparty/cpplinq" "thirdparty/cpp-httplib" + "thirdparty/MD5" "tests" "tests/dCommonTests" @@ -320,7 +321,7 @@ add_subdirectory(dPhysics) add_subdirectory(dServer) # Create a list of common libraries shared between all binaries -set(COMMON_LIBRARIES "dCommon" "dDatabase" "dNet" "raknet" "mariadbConnCpp" "magic_enum") +set(COMMON_LIBRARIES "dCommon" "dDatabase" "dNet" "raknet" "mariadbConnCpp" "magic_enum" "MD5") # Add platform specific common libraries if(UNIX) diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt index 32f24028..c5fff63a 100644 --- a/dCommon/CMakeLists.txt +++ b/dCommon/CMakeLists.txt @@ -8,11 +8,9 @@ set(DCOMMON_SOURCES "Game.cpp" "GeneralUtils.cpp" "LDFFormat.cpp" - "MD5.cpp" "Metrics.cpp" "NiPoint3.cpp" "NiQuaternion.cpp" - "SHA512.cpp" "Demangler.cpp" "ZCompression.cpp" "BrickByBrickFix.cpp" @@ -68,8 +66,3 @@ else () endif () target_link_libraries(dCommon ZLIB::ZLIB) - -# Disable deprecation warnings on MD5.cpp and SHA512.cpp for Apple Clang -if (APPLE) - set_source_files_properties("MD5.cpp" "SHA512.cpp" PROPERTIES COMPILE_FLAGS "-Wno-deprecated-declarations") -endif() diff --git a/dCommon/SHA512.cpp b/dCommon/SHA512.cpp deleted file mode 100644 index e3c2d9f7..00000000 --- a/dCommon/SHA512.cpp +++ /dev/null @@ -1,154 +0,0 @@ -// Source: http://www.zedwood.com/article/cpp-sha512-function - -#include "SHA512.h" - -#include -#include - -const unsigned long long SHA512::sha512_k[80] = //ULL = uint64 -{ 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, - 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, - 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, - 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, - 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, - 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, - 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, - 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, - 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, - 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, - 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, - 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, - 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, - 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, - 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, - 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, - 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, - 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, - 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, - 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, - 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, - 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, - 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, - 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, - 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, - 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, - 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, - 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, - 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, - 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, - 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, - 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, - 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, - 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, - 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, - 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, - 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, - 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, - 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, - 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL }; - -void SHA512::transform(const unsigned char* message, unsigned int block_nb) { - uint64 w[80]; - uint64 wv[8]; - uint64 t1, t2; - const unsigned char* sub_block; - int i, j; - for (i = 0; i < (int)block_nb; i++) { - sub_block = message + (i << 7); - for (j = 0; j < 16; j++) { - SHA2_PACK64(&sub_block[j << 3], &w[j]); - } - for (j = 16; j < 80; j++) { - w[j] = SHA512_F4(w[j - 2]) + w[j - 7] + SHA512_F3(w[j - 15]) + w[j - 16]; - } - for (j = 0; j < 8; j++) { - wv[j] = m_h[j]; - } - for (j = 0; j < 80; j++) { - t1 = wv[7] + SHA512_F2(wv[4]) + SHA2_CH(wv[4], wv[5], wv[6]) - + sha512_k[j] + w[j]; - t2 = SHA512_F1(wv[0]) + SHA2_MAJ(wv[0], wv[1], wv[2]); - wv[7] = wv[6]; - wv[6] = wv[5]; - wv[5] = wv[4]; - wv[4] = wv[3] + t1; - wv[3] = wv[2]; - wv[2] = wv[1]; - wv[1] = wv[0]; - wv[0] = t1 + t2; - } - for (j = 0; j < 8; j++) { - m_h[j] += wv[j]; - } - - } -} - -void SHA512::init() { - m_h[0] = 0x6a09e667f3bcc908ULL; - m_h[1] = 0xbb67ae8584caa73bULL; - m_h[2] = 0x3c6ef372fe94f82bULL; - m_h[3] = 0xa54ff53a5f1d36f1ULL; - m_h[4] = 0x510e527fade682d1ULL; - m_h[5] = 0x9b05688c2b3e6c1fULL; - m_h[6] = 0x1f83d9abfb41bd6bULL; - m_h[7] = 0x5be0cd19137e2179ULL; - m_len = 0; - m_tot_len = 0; -} - -void SHA512::update(const unsigned char* message, unsigned int len) { - unsigned int block_nb; - unsigned int new_len, rem_len, tmp_len; - const unsigned char* shifted_message; - tmp_len = SHA384_512_BLOCK_SIZE - m_len; - rem_len = len < tmp_len ? len : tmp_len; - memcpy(&m_block[m_len], message, rem_len); - if (m_len + len < SHA384_512_BLOCK_SIZE) { - m_len += len; - return; - } - new_len = len - rem_len; - block_nb = new_len / SHA384_512_BLOCK_SIZE; - shifted_message = message + rem_len; - transform(m_block, 1); - transform(shifted_message, block_nb); - rem_len = new_len % SHA384_512_BLOCK_SIZE; - memcpy(m_block, &shifted_message[block_nb << 7], rem_len); - m_len = rem_len; - m_tot_len += (block_nb + 1) << 7; -} - -void SHA512::final(unsigned char* digest) { - unsigned int block_nb; - unsigned int pm_len; - unsigned int len_b; - int i; - block_nb = 1 + ((SHA384_512_BLOCK_SIZE - 17) - < (m_len % SHA384_512_BLOCK_SIZE)); - len_b = (m_tot_len + m_len) << 3; - pm_len = block_nb << 7; - memset(m_block + m_len, 0, pm_len - m_len); - m_block[m_len] = 0x80; - SHA2_UNPACK32(len_b, m_block + pm_len - 4); - transform(m_block, block_nb); - for (i = 0; i < 8; i++) { - SHA2_UNPACK64(m_h[i], &digest[i << 3]); - } -} - -std::string sha512(std::string input) { - unsigned char digest[SHA512::DIGEST_SIZE]; - memset(digest, 0, SHA512::DIGEST_SIZE); - class SHA512 ctx; - ctx.init(); - ctx.update((unsigned char*)input.c_str(), input.length()); - ctx.final(digest); - - char buf[2 * SHA512::DIGEST_SIZE + 1]; - buf[2 * SHA512::DIGEST_SIZE] = 0; - for (int i = 0; i < SHA512::DIGEST_SIZE; i++) - sprintf(buf + i * 2, "%02x", digest[i]); - - return std::string(buf); -} diff --git a/dCommon/SHA512.h b/dCommon/SHA512.h deleted file mode 100644 index 512fa645..00000000 --- a/dCommon/SHA512.h +++ /dev/null @@ -1,68 +0,0 @@ -#pragma once - -// C++ -#include - -class SHA512 { -protected: - typedef unsigned char uint8; - typedef unsigned int uint32; - typedef unsigned long long uint64; - - const static uint64 sha512_k[]; - static const unsigned int SHA384_512_BLOCK_SIZE = (1024 / 8); - -public: - void init(); - void update(const unsigned char* message, unsigned int len); - void final(unsigned char* digest); - static const unsigned int DIGEST_SIZE = (512 / 8); - -protected: - void transform(const unsigned char* message, unsigned int block_nb); - unsigned int m_tot_len; - unsigned int m_len; - unsigned char m_block[2 * SHA384_512_BLOCK_SIZE]; - uint64 m_h[8]; -}; - -std::string sha512(std::string input); - -#define SHA2_SHFR(x, n) (x >> n) -#define SHA2_ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n))) -#define SHA2_ROTL(x, n) ((x << n) | (x >> ((sizeof(x) << 3) - n))) -#define SHA2_CH(x, y, z) ((x & y) ^ (~x & z)) -#define SHA2_MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z)) -#define SHA512_F1(x) (SHA2_ROTR(x, 28) ^ SHA2_ROTR(x, 34) ^ SHA2_ROTR(x, 39)) -#define SHA512_F2(x) (SHA2_ROTR(x, 14) ^ SHA2_ROTR(x, 18) ^ SHA2_ROTR(x, 41)) -#define SHA512_F3(x) (SHA2_ROTR(x, 1) ^ SHA2_ROTR(x, 8) ^ SHA2_SHFR(x, 7)) -#define SHA512_F4(x) (SHA2_ROTR(x, 19) ^ SHA2_ROTR(x, 61) ^ SHA2_SHFR(x, 6)) -#define SHA2_UNPACK32(x, str) \ -{ \ -*((str) + 3) = (uint8) ((x) ); \ -*((str) + 2) = (uint8) ((x) >> 8); \ -*((str) + 1) = (uint8) ((x) >> 16); \ -*((str) + 0) = (uint8) ((x) >> 24); \ -} -#define SHA2_UNPACK64(x, str) \ -{ \ -*((str) + 7) = (uint8) ((x) ); \ -*((str) + 6) = (uint8) ((x) >> 8); \ -*((str) + 5) = (uint8) ((x) >> 16); \ -*((str) + 4) = (uint8) ((x) >> 24); \ -*((str) + 3) = (uint8) ((x) >> 32); \ -*((str) + 2) = (uint8) ((x) >> 40); \ -*((str) + 1) = (uint8) ((x) >> 48); \ -*((str) + 0) = (uint8) ((x) >> 56); \ -} -#define SHA2_PACK64(str, x) \ -{ \ -*(x) = ((uint64) *((str) + 7) ) \ -| ((uint64) *((str) + 6) << 8) \ -| ((uint64) *((str) + 5) << 16) \ -| ((uint64) *((str) + 4) << 24) \ -| ((uint64) *((str) + 3) << 32) \ -| ((uint64) *((str) + 2) << 40) \ -| ((uint64) *((str) + 1) << 48) \ -| ((uint64) *((str) + 0) << 56); \ -} diff --git a/dNet/AuthPackets.cpp b/dNet/AuthPackets.cpp index 2597c576..9982f89e 100644 --- a/dNet/AuthPackets.cpp +++ b/dNet/AuthPackets.cpp @@ -7,7 +7,6 @@ #include "Database.h" #include "ZoneInstanceManager.h" #include "MD5.h" -#include "SHA512.h" #include "GeneralUtils.h" #include diff --git a/thirdparty/CMakeLists.txt b/thirdparty/CMakeLists.txt index 11d278c0..40c81544 100644 --- a/thirdparty/CMakeLists.txt +++ b/thirdparty/CMakeLists.txt @@ -57,3 +57,5 @@ if(UNIX AND NOT APPLE) include_directories(${backtrace_SOURCE_DIR}) endif() endif() + +add_subdirectory(MD5) diff --git a/thirdparty/MD5/CMakeLists.txt b/thirdparty/MD5/CMakeLists.txt new file mode 100644 index 00000000..755b4519 --- /dev/null +++ b/thirdparty/MD5/CMakeLists.txt @@ -0,0 +1,6 @@ +add_library(MD5 "MD5.cpp") + +# Disable deprecation warnings on MD5.cpp for Apple Clang +if (APPLE) + set_source_files_properties("MD5.cpp" PROPERTIES COMPILE_FLAGS "-Wno-deprecated-declarations") +endif() diff --git a/dCommon/MD5.cpp b/thirdparty/MD5/MD5.cpp similarity index 100% rename from dCommon/MD5.cpp rename to thirdparty/MD5/MD5.cpp diff --git a/dCommon/MD5.h b/thirdparty/MD5/MD5.h similarity index 100% rename from dCommon/MD5.h rename to thirdparty/MD5/MD5.h From 0c1ee0513d1d3fb19709da8c9bb2513290639259 Mon Sep 17 00:00:00 2001 From: jadebenn Date: Sat, 10 Feb 2024 05:05:25 -0600 Subject: [PATCH 15/50] refactor: Change TryParse implementation (#1442) * Changed how the TryParse function works (and also did some general cleanup along the way) * Update noexcept attributes (verified these are correct) * Add fp overload for MacOS functionality * resolving some feedback * Split out unrelated changes to CleanupRoundup branch * Update in response to feedback * the consequences of emo's member variable renaming request * Revert "the consequences of emo's member variable renaming request" This reverts commit bf318caeda34f4439c1769fd7d5b77d341f7f646. * Fully revert renaming attempt * Revert "the consequences of emo's member variable renaming request" This reverts commit bf318caeda34f4439c1769fd7d5b77d341f7f646. Fully revert renaming attempt * Created ClientVersion.h and moved the client version defaults to it * Fix partial parsing and MacOS floating point errors * attempting fix to MacOS compiler error * syntax pass (should be the last commit unless the CI fails) * ah, wait, forgot to uncomment the preprocessor statements for MacOS. THIS should be the last commit pending CI * Okay, one last thing I noticed: We were including C headers here. Now they're C++ headers. Pinky swear this is it! * typo and I am OCD. please let this be the last * hash is usally but not always noexcept, so the specifier should go * Address MOST of the feedback * address the claim codes issue --- dAuthServer/AuthServer.cpp | 8 +- dChatServer/ChatServer.cpp | 9 +- dChatServer/PlayerContainer.cpp | 6 +- dCommon/GeneralUtils.cpp | 4 - dCommon/GeneralUtils.h | 184 ++++---- dCommon/LDFFormat.cpp | 38 +- dCommon/dClient/CMakeLists.txt | 2 +- dCommon/dClient/ClientVersion.h | 12 + dGame/Entity.cpp | 6 +- dGame/Entity.h | 10 +- dGame/dComponents/ActivityComponent.cpp | 3 +- dGame/dComponents/QuickBuildComponent.cpp | 9 +- dGame/dComponents/QuickBuildComponent.h | 2 +- dGame/dComponents/RenderComponent.cpp | 10 +- dGame/dComponents/TriggerComponent.cpp | 59 ++- dGame/dInventory/Item.cpp | 8 +- dGame/dInventory/ItemSet.cpp | 6 +- dGame/dMission/MissionTask.cpp | 12 +- .../BehaviorMessageBase.cpp | 7 +- dGame/dUtilities/Preconditions.cpp | 6 +- dGame/dUtilities/SlashCommandHandler.cpp | 400 +++++++++--------- dMasterServer/InstanceManager.cpp | 3 +- dMasterServer/InstanceManager.h | 2 +- dMasterServer/MasterServer.cpp | 3 +- dNet/AuthPackets.cpp | 23 +- dPhysics/dpWorld.cpp | 10 +- .../02_server/Map/AM/AmDropshipComputer.cpp | 14 +- dScripts/02_server/Map/AM/AmSkullkinTower.cpp | 9 +- .../Map/AM/AmTemplateSkillVolume.cpp | 9 +- dScripts/ChooseYourDestinationNsToNt.cpp | 10 +- dScripts/ai/FV/FvBrickPuzzleServer.cpp | 16 +- dWorldServer/WorldServer.cpp | 3 +- dZoneManager/Level.cpp | 13 +- 33 files changed, 463 insertions(+), 453 deletions(-) create mode 100644 dCommon/dClient/ClientVersion.h diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index 5593f0e1..476e1a68 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -82,11 +82,11 @@ int main(int argc, char** argv) { Game::randomEngine = std::mt19937(time(0)); //It's safe to pass 'localhost' here, as the IP is only used as the external IP. - uint32_t maxClients = 999; - uint32_t ourPort = 1001; //LU client is hardcoded to use this for auth port, so I'm making it the default. std::string ourIP = "localhost"; - GeneralUtils::TryParse(Game::config->GetValue("max_clients"), maxClients); - GeneralUtils::TryParse(Game::config->GetValue("auth_server_port"), ourPort); + const uint32_t maxClients = GeneralUtils::TryParse(Game::config->GetValue("max_clients")).value_or(999); + + //LU client is hardcoded to use this for auth port, so I'm making it the default. + const uint32_t ourPort = GeneralUtils::TryParse(Game::config->GetValue("auth_server_port")).value_or(1001); const auto externalIPString = Game::config->GetValue("external_ip"); if (!externalIPString.empty()) ourIP = externalIPString; diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index d04cbd01..44957042 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -99,18 +99,15 @@ int main(int argc, char** argv) { masterPort = masterInfo->port; } //It's safe to pass 'localhost' here, as the IP is only used as the external IP. - uint32_t maxClients = 999; - uint32_t ourPort = 1501; std::string ourIP = "localhost"; - GeneralUtils::TryParse(Game::config->GetValue("max_clients"), maxClients); - GeneralUtils::TryParse(Game::config->GetValue("chat_server_port"), ourPort); + const uint32_t maxClients = GeneralUtils::TryParse(Game::config->GetValue("max_clients")).value_or(999); + const uint32_t ourPort = GeneralUtils::TryParse(Game::config->GetValue("chat_server_port")).value_or(1501); const auto externalIPString = Game::config->GetValue("external_ip"); if (!externalIPString.empty()) ourIP = externalIPString; Game::server = new dServer(ourIP, ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Chat, Game::config, &Game::lastSignal); - bool dontGenerateDCF = false; - GeneralUtils::TryParse(Game::config->GetValue("dont_generate_dcf"), dontGenerateDCF); + const bool dontGenerateDCF = GeneralUtils::TryParse(Game::config->GetValue("dont_generate_dcf")).value_or(false); Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", dontGenerateDCF); Game::randomEngine = std::mt19937(time(0)); diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index 95bafd8b..7d8d7d97 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -15,8 +15,10 @@ #include "dConfig.h" void PlayerContainer::Initialize() { - GeneralUtils::TryParse(Game::config->GetValue("max_number_of_best_friends"), m_MaxNumberOfBestFriends); - GeneralUtils::TryParse(Game::config->GetValue("max_number_of_friends"), m_MaxNumberOfFriends); + m_MaxNumberOfBestFriends = + GeneralUtils::TryParse(Game::config->GetValue("max_number_of_best_friends")).value_or(m_MaxNumberOfBestFriends); + m_MaxNumberOfFriends = + GeneralUtils::TryParse(Game::config->GetValue("max_number_of_friends")).value_or(m_MaxNumberOfFriends); } PlayerContainer::~PlayerContainer() { diff --git a/dCommon/GeneralUtils.cpp b/dCommon/GeneralUtils.cpp index b45165fa..78cf4f48 100644 --- a/dCommon/GeneralUtils.cpp +++ b/dCommon/GeneralUtils.cpp @@ -319,7 +319,3 @@ std::vector GeneralUtils::GetSqlFileNamesFromFolder(const std::stri return sortedFiles; } - -bool GeneralUtils::TryParse(const std::string& x, const std::string& y, const std::string& z, NiPoint3& dst) { - return TryParse(x.c_str(), dst.x) && TryParse(y.c_str(), dst.y) && TryParse(z.c_str(), dst.z); -} diff --git a/dCommon/GeneralUtils.h b/dCommon/GeneralUtils.h index 37291ab8..15659912 100644 --- a/dCommon/GeneralUtils.h +++ b/dCommon/GeneralUtils.h @@ -1,17 +1,20 @@ #pragma once // C++ -#include +#include +#include #include -#include +#include #include -#include +#include +#include #include #include #include #include "BitStream.h" #include "NiPoint3.h" +#include "dPlatforms.h" #include "Game.h" #include "Logger.h" @@ -123,90 +126,125 @@ namespace GeneralUtils { std::vector GetSqlFileNamesFromFolder(const std::string& folder); + // Concept constraining to enum types template - T Parse(const char* value); - - template <> - inline bool Parse(const char* value) { - return std::stoi(value); - } - - template <> - inline int32_t Parse(const char* value) { - return std::stoi(value); - } - - template <> - inline int64_t Parse(const char* value) { - return std::stoll(value); - } - - template <> - inline float Parse(const char* value) { - return std::stof(value); - } - - template <> - inline double Parse(const char* value) { - return std::stod(value); - } - - template <> - inline uint16_t Parse(const char* value) { - return std::stoul(value); - } - - template <> - inline uint32_t Parse(const char* value) { - return std::stoul(value); - } - - template <> - inline uint64_t Parse(const char* value) { - return std::stoull(value); - } - - template <> - inline eInventoryType Parse(const char* value) { - return static_cast(std::stoul(value)); - } - - template <> - inline eReplicaComponentType Parse(const char* value) { - return static_cast(std::stoul(value)); - } + concept Enum = std::is_enum_v; + // Concept constraining to numeric types template - bool TryParse(const char* value, T& dst) { - try { - dst = Parse(value); + concept Numeric = std::integral || Enum || std::floating_point; - return true; - } catch (...) { - return false; + // Concept trickery to enable parsing underlying numeric types + template + struct numeric_parse { using type = T; }; + + // If an enum, present an alias to its underlying type for parsing + template requires Enum + struct numeric_parse { using type = std::underlying_type_t; }; + + // If a boolean, present an alias to an intermediate integral type for parsing + template requires std::same_as + struct numeric_parse { using type = uint32_t; }; + + // Shorthand type alias + template + using numeric_parse_t = numeric_parse::type; + + /** + * For numeric values: Parses a string_view and returns an optional variable depending on the result. + * @param str The string_view to be evaluated + * @returns An std::optional containing the desired value if it is equivalent to the string + */ + template + [[nodiscard]] std::optional TryParse(const std::string_view str) { + numeric_parse_t result; + + const char* const strEnd = str.data() + str.size(); + const auto [parseEnd, ec] = std::from_chars(str.data(), strEnd, result); + const bool isParsed = parseEnd == strEnd && ec == std::errc{}; + + return isParsed ? static_cast(result) : std::optional{}; + } + +#ifdef DARKFLAME_PLATFORM_MACOS + + // Anonymous namespace containing MacOS floating-point parse function specializations + namespace { + template + [[nodiscard]] T Parse(const std::string_view str, size_t* parseNum); + + template <> + [[nodiscard]] float Parse(const std::string_view str, size_t* parseNum) { + return std::stof(std::string{ str }, parseNum); + } + + template <> + [[nodiscard]] double Parse(const std::string_view str, size_t* parseNum) { + return std::stod(std::string{ str }, parseNum); + } + + template <> + [[nodiscard]] long double Parse(const std::string_view str, size_t* parseNum) { + return std::stold(std::string{ str }, parseNum); } } + /** + * For floating-point values: Parses a string_view and returns an optional variable depending on the result. + * Note that this function overload is only included for MacOS, as from_chars will fulfill its purpose otherwise. + * @param str The string_view to be evaluated + * @returns An std::optional containing the desired value if it is equivalent to the string + */ + template + [[nodiscard]] std::optional TryParse(const std::string_view str) noexcept try { + size_t parseNum; + const T result = Parse(str, &parseNum); + const bool isParsed = str.length() == parseNum; + + return isParsed ? result : std::optional{}; + } catch (...) { + return std::nullopt; + } + +#endif + + /** + * The TryParse overload for handling NiPoint3 by passing 3 seperate string references + * @param strX The string representing the X coordinate + * @param strY The string representing the Y coordinate + * @param strZ The string representing the Z coordinate + * @returns An std::optional containing the desired NiPoint3 if it can be constructed from the string parameters + */ template - T Parse(const std::string& value) { - return Parse(value.c_str()); + [[nodiscard]] std::optional TryParse(const std::string& strX, const std::string& strY, const std::string& strZ) { + const auto x = TryParse(strX); + if (!x) return std::nullopt; + + const auto y = TryParse(strY); + if (!y) return std::nullopt; + + const auto z = TryParse(strZ); + return z ? std::make_optional(x.value(), y.value(), z.value()) : std::nullopt; + } + + /** + * The TryParse overload for handling NiPoint3 by passingn a reference to a vector of three strings + * @param str The string vector representing the X, Y, and Xcoordinates + * @returns An std::optional containing the desired NiPoint3 if it can be constructed from the string parameters + */ + template + [[nodiscard]] std::optional TryParse(const std::vector& str) { + return (str.size() == 3) ? TryParse(str[0], str[1], str[2]) : std::nullopt; } template - bool TryParse(const std::string& value, T& dst) { - return TryParse(value.c_str(), dst); - } - - bool TryParse(const std::string& x, const std::string& y, const std::string& z, NiPoint3& dst); - - template std::u16string to_u16string(T value) { return GeneralUtils::ASCIIToUTF16(std::to_string(value)); } // From boost::hash_combine template - void hash_combine(std::size_t& s, const T& v) { + constexpr void hash_combine(std::size_t& s, const T& v) { std::hash h; s ^= h(v) + 0x9e3779b9 + (s << 6) + (s >> 2); } @@ -239,10 +277,8 @@ namespace GeneralUtils { * @param entry Enum entry to cast * @returns The enum entry's value in its underlying type */ - template - inline constexpr typename std::underlying_type_t CastUnderlyingType(const eType entry) { - static_assert(std::is_enum_v, "Not an enum"); - + template + constexpr typename std::underlying_type_t CastUnderlyingType(const eType entry) noexcept { return static_cast>(entry); } diff --git a/dCommon/LDFFormat.cpp b/dCommon/LDFFormat.cpp index 67f6a630..da28ae6e 100644 --- a/dCommon/LDFFormat.cpp +++ b/dCommon/LDFFormat.cpp @@ -61,33 +61,33 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } case LDF_TYPE_S32: { - int32_t data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid int32 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } case LDF_TYPE_FLOAT: { - float data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid float value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } case LDF_TYPE_DOUBLE: { - double data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid double value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } @@ -100,10 +100,12 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } else if (ldfTypeAndValue.second == "false") { data = 0; } else { - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto dataOptional = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!dataOptional) { LOG("Warning: Attempted to process invalid uint32 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } + data = dataOptional.value(); } returnValue = new LDFData(key, data); @@ -118,10 +120,12 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } else if (ldfTypeAndValue.second == "false") { data = false; } else { - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto dataOptional = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!dataOptional) { LOG("Warning: Attempted to process invalid bool value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } + data = dataOptional.value(); } returnValue = new LDFData(key, data); @@ -129,22 +133,22 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } case LDF_TYPE_U64: { - uint64_t data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid uint64 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } case LDF_TYPE_OBJID: { - LWOOBJID data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid LWOOBJID value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } diff --git a/dCommon/dClient/CMakeLists.txt b/dCommon/dClient/CMakeLists.txt index 69bb1712..017a22a5 100644 --- a/dCommon/dClient/CMakeLists.txt +++ b/dCommon/dClient/CMakeLists.txt @@ -1,6 +1,6 @@ set(DCOMMON_DCLIENT_SOURCES + "AssetManager.cpp" "PackIndex.cpp" "Pack.cpp" - "AssetManager.cpp" PARENT_SCOPE ) diff --git a/dCommon/dClient/ClientVersion.h b/dCommon/dClient/ClientVersion.h new file mode 100644 index 00000000..393103ab --- /dev/null +++ b/dCommon/dClient/ClientVersion.h @@ -0,0 +1,12 @@ +#ifndef __CLIENTVERSION_H__ +#define __CLIENTVERSION_H__ + +#include + +namespace ClientVersion { + constexpr uint16_t major = 1; + constexpr uint16_t current = 10; + constexpr uint16_t minor = 64; +} + +#endif // !__CLIENTVERSION_H__ diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 84bdca21..16169887 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -452,10 +452,10 @@ void Entity::Initialize() { if (!setFaction.empty()) { // TODO also split on space here however we do not have a general util for splitting on multiple characters yet. std::vector factionsToAdd = GeneralUtils::SplitString(setFaction, ';'); - int32_t factionToAdd; for (const auto faction : factionsToAdd) { - if (GeneralUtils::TryParse(faction, factionToAdd)) { - comp->AddFaction(factionToAdd, true); + const auto factionToAdd = GeneralUtils::TryParse(faction); + if (factionToAdd) { + comp->AddFaction(factionToAdd.value(), true); } } } diff --git a/dGame/Entity.h b/dGame/Entity.h index eb6eb956..6546e458 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -395,14 +395,8 @@ const T& Entity::GetVar(const std::u16string& name) const { template T Entity::GetVarAs(const std::u16string& name) const { const auto data = GetVarAsString(name); - - T value; - - if (!GeneralUtils::TryParse(data, value)) { - return LDFData::Default; - } - - return value; + + return GeneralUtils::TryParse(data).value_or(LDFData::Default); } template diff --git a/dGame/dComponents/ActivityComponent.cpp b/dGame/dComponents/ActivityComponent.cpp index 376251d2..49ca4faf 100644 --- a/dGame/dComponents/ActivityComponent.cpp +++ b/dGame/dComponents/ActivityComponent.cpp @@ -83,7 +83,8 @@ void ActivityComponent::LoadActivityData(const int32_t activityId) { if (m_ActivityInfo.instanceMapID == -1) { const auto& transferOverride = m_Parent->GetVarAsString(u"transferZoneID"); if (!transferOverride.empty()) { - GeneralUtils::TryParse(transferOverride, m_ActivityInfo.instanceMapID); + m_ActivityInfo.instanceMapID = + GeneralUtils::TryParse(transferOverride).value_or(m_ActivityInfo.instanceMapID); } } } diff --git a/dGame/dComponents/QuickBuildComponent.cpp b/dGame/dComponents/QuickBuildComponent.cpp index 1e745d8a..2514f194 100644 --- a/dGame/dComponents/QuickBuildComponent.cpp +++ b/dGame/dComponents/QuickBuildComponent.cpp @@ -33,10 +33,9 @@ QuickBuildComponent::QuickBuildComponent(Entity* entity) : Component(entity) { // Should a setting that has the build activator position exist, fetch that setting here and parse it for position. // It is assumed that the user who sets this setting uses the correct character delimiter (character 31 or in hex 0x1F) auto positionAsVector = GeneralUtils::SplitString(m_Parent->GetVarAsString(u"rebuild_activators"), 0x1F); - if (positionAsVector.size() == 3 && - GeneralUtils::TryParse(positionAsVector[0], m_ActivatorPosition.x) && - GeneralUtils::TryParse(positionAsVector[1], m_ActivatorPosition.y) && - GeneralUtils::TryParse(positionAsVector[2], m_ActivatorPosition.z)) { + const auto activatorPositionValid = GeneralUtils::TryParse(positionAsVector); + if (positionAsVector.size() == 3 && activatorPositionValid) { + m_ActivatorPosition = activatorPositionValid.value(); } else { LOG("Failed to find activator position for lot %i. Defaulting to parents position.", m_Parent->GetLOT()); m_ActivatorPosition = m_Parent->GetPosition(); @@ -328,7 +327,7 @@ float QuickBuildComponent::GetTimeBeforeSmash() { return m_TimeBeforeSmash; } -eQuickBuildState QuickBuildComponent::GetState() { +eQuickBuildState QuickBuildComponent::GetState() const noexcept { return m_State; } diff --git a/dGame/dComponents/QuickBuildComponent.h b/dGame/dComponents/QuickBuildComponent.h index d989bc51..d9cc4190 100644 --- a/dGame/dComponents/QuickBuildComponent.h +++ b/dGame/dComponents/QuickBuildComponent.h @@ -173,7 +173,7 @@ public: * Returns the current quickbuild state * @return the current quickbuild state */ - eQuickBuildState GetState(); + [[nodiscard]] eQuickBuildState GetState() const noexcept; /** * Returns the player that is currently building this quickbuild diff --git a/dGame/dComponents/RenderComponent.cpp b/dGame/dComponents/RenderComponent.cpp index d3c74f78..118e4847 100644 --- a/dGame/dComponents/RenderComponent.cpp +++ b/dGame/dComponents/RenderComponent.cpp @@ -30,13 +30,15 @@ RenderComponent::RenderComponent(Entity* const parentEntity, const int32_t compo auto* animationsTable = CDClientManager::GetTable(); auto groupIdsSplit = GeneralUtils::SplitString(animationGroupIDs, ','); for (auto& groupId : groupIdsSplit) { - int32_t groupIdInt; - if (!GeneralUtils::TryParse(groupId, groupIdInt)) { + const auto groupIdInt = GeneralUtils::TryParse(groupId); + + if (!groupIdInt) { LOG("bad animation group Id %s", groupId.c_str()); continue; } - m_animationGroupIds.push_back(groupIdInt); - animationsTable->CacheAnimationGroup(groupIdInt); + + m_animationGroupIds.push_back(groupIdInt.value()); + animationsTable->CacheAnimationGroup(groupIdInt.value()); } } } diff --git a/dGame/dComponents/TriggerComponent.cpp b/dGame/dComponents/TriggerComponent.cpp index bb297dbc..5d4415f8 100644 --- a/dGame/dComponents/TriggerComponent.cpp +++ b/dGame/dComponents/TriggerComponent.cpp @@ -21,10 +21,8 @@ TriggerComponent::TriggerComponent(Entity* parent, const std::string triggerInfo std::vector tokens = GeneralUtils::SplitString(triggerInfo, ':'); - uint32_t sceneID; - GeneralUtils::TryParse(tokens.at(0), sceneID); - uint32_t triggerID; - GeneralUtils::TryParse(tokens.at(1), triggerID); + const auto sceneID = GeneralUtils::TryParse(tokens.at(0)).value_or(0); + const auto triggerID = GeneralUtils::TryParse(tokens.at(1)).value_or(0); m_Trigger = Game::zoneManager->GetZone()->GetTrigger(sceneID, triggerID); @@ -190,9 +188,8 @@ void TriggerComponent::HandleFireEvent(Entity* targetEntity, std::string args) { } void TriggerComponent::HandleDestroyObject(Entity* targetEntity, std::string args){ - uint32_t killType; - GeneralUtils::TryParse(args, killType); - targetEntity->Smash(m_Parent->GetObjectID(), static_cast(killType)); + const eKillType killType = GeneralUtils::TryParse(args).value_or(eKillType::VIOLENT); + targetEntity->Smash(m_Parent->GetObjectID(), killType); } void TriggerComponent::HandleToggleTrigger(Entity* targetEntity, std::string args){ @@ -216,9 +213,8 @@ void TriggerComponent::HandleResetRebuild(Entity* targetEntity, std::string args void TriggerComponent::HandleMoveObject(Entity* targetEntity, std::vector argArray){ if (argArray.size() <= 2) return; - auto position = targetEntity->GetPosition(); - NiPoint3 offset = NiPoint3Constant::ZERO; - GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), offset); + NiPoint3 position = targetEntity->GetPosition(); + const NiPoint3 offset = GeneralUtils::TryParse(argArray).value_or(NiPoint3Constant::ZERO); position += offset; targetEntity->SetPosition(position); @@ -227,8 +223,7 @@ void TriggerComponent::HandleMoveObject(Entity* targetEntity, std::vector argArray){ if (argArray.size() <= 2) return; - NiPoint3 vector = NiPoint3Constant::ZERO; - GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), vector); + const NiPoint3 vector = GeneralUtils::TryParse(argArray).value_or(NiPoint3Constant::ZERO); NiQuaternion rotation = NiQuaternion::FromEulerAngles(vector); targetEntity->SetRotation(rotation); @@ -245,8 +240,7 @@ void TriggerComponent::HandlePushObject(Entity* targetEntity, std::vectorSetPhysicsEffectActive(true); phantomPhysicsComponent->SetEffectType(ePhysicsEffectType::PUSH); phantomPhysicsComponent->SetDirectionalMultiplier(1); - NiPoint3 direction = NiPoint3Constant::ZERO; - GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), direction); + const NiPoint3 direction = GeneralUtils::TryParse(argArray).value_or(NiPoint3Constant::ZERO); phantomPhysicsComponent->SetDirection(direction); Game::entityManager->SerializeEntity(m_Parent); @@ -259,8 +253,8 @@ void TriggerComponent::HandleRepelObject(Entity* targetEntity, std::string args) LOG_DEBUG("Phantom Physics component not found!"); return; } - float forceMultiplier; - GeneralUtils::TryParse(args, forceMultiplier); + const float forceMultiplier = GeneralUtils::TryParse(args).value_or(1.0f); + phantomPhysicsComponent->SetPhysicsEffectActive(true); phantomPhysicsComponent->SetEffectType(ePhysicsEffectType::REPULSE); phantomPhysicsComponent->SetDirectionalMultiplier(forceMultiplier); @@ -279,11 +273,10 @@ void TriggerComponent::HandleRepelObject(Entity* targetEntity, std::string args) void TriggerComponent::HandleSetTimer(Entity* targetEntity, std::vector argArray){ if (argArray.size() != 2) { - LOG_DEBUG("Not ehought variables!"); + LOG_DEBUG("Not enough variables!"); return; } - float time = 0.0; - GeneralUtils::TryParse(argArray.at(1), time); + const float time = GeneralUtils::TryParse(argArray.at(1)).value_or(0.0f); m_Parent->AddTimer(argArray.at(0), time); } @@ -299,7 +292,7 @@ void TriggerComponent::HandlePlayCinematic(Entity* targetEntity, std::vector= 2) { - GeneralUtils::TryParse(argArray.at(1), leadIn); + leadIn = GeneralUtils::TryParse(argArray.at(1)).value_or(leadIn); if (argArray.size() >= 3 && argArray.at(2) == "wait") { wait = eEndBehavior::WAIT; if (argArray.size() >= 4 && argArray.at(3) == "unlock") { @@ -344,12 +337,16 @@ void TriggerComponent::HandleUpdateMission(Entity* targetEntity, std::vector argArray) { if (argArray.size() < 3) return; - int32_t effectID = 0; - if (!GeneralUtils::TryParse(argArray.at(1), effectID)) return; + const auto effectID = GeneralUtils::TryParse(argArray.at(1)); + if (!effectID) return; std::u16string effectType = GeneralUtils::UTF8ToUTF16(argArray.at(2)); + float priority = 1; - if (argArray.size() == 4) GeneralUtils::TryParse(argArray.at(3), priority); - GameMessages::SendPlayFXEffect(targetEntity, effectID, effectType, argArray.at(0), LWOOBJID_EMPTY, priority); + if (argArray.size() == 4) { + priority = GeneralUtils::TryParse(argArray.at(3)).value_or(priority); + } + + GameMessages::SendPlayFXEffect(targetEntity, effectID.value(), effectType, argArray.at(0), LWOOBJID_EMPTY, priority); } void TriggerComponent::HandleCastSkill(Entity* targetEntity, std::string args){ @@ -358,8 +355,7 @@ void TriggerComponent::HandleCastSkill(Entity* targetEntity, std::string args){ LOG_DEBUG("Skill component not found!"); return; } - uint32_t skillId; - GeneralUtils::TryParse(args, skillId); + const uint32_t skillId = GeneralUtils::TryParse(args).value_or(0); skillComponent->CastSkill(skillId, targetEntity->GetObjectID()); } @@ -381,17 +377,16 @@ void TriggerComponent::HandleSetPhysicsVolumeEffect(Entity* targetEntity, std::v phantomPhysicsComponent->SetEffectType(effectType); phantomPhysicsComponent->SetDirectionalMultiplier(std::stof(argArray.at(1))); if (argArray.size() > 4) { - NiPoint3 direction = NiPoint3Constant::ZERO; - GeneralUtils::TryParse(argArray.at(2), argArray.at(3), argArray.at(4), direction); + const NiPoint3 direction = + GeneralUtils::TryParse(argArray.at(2), argArray.at(3), argArray.at(4)).value_or(NiPoint3Constant::ZERO); + phantomPhysicsComponent->SetDirection(direction); } if (argArray.size() > 5) { - uint32_t min; - GeneralUtils::TryParse(argArray.at(6), min); + const uint32_t min = GeneralUtils::TryParse(argArray.at(6)).value_or(0); phantomPhysicsComponent->SetMin(min); - uint32_t max; - GeneralUtils::TryParse(argArray.at(7), max); + const uint32_t max = GeneralUtils::TryParse(argArray.at(7)).value_or(0); phantomPhysicsComponent->SetMax(max); } diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 55b0a2d0..d3f15315 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -468,14 +468,14 @@ void Item::DisassembleModel(uint32_t numToDismantle) { // First iteration gets the count std::map parts; while (currentBrick) { - auto* designID = currentBrick->Attribute("designID"); + const char* const designID = currentBrick->Attribute("designID"); if (designID) { - uint32_t designId; - if (!GeneralUtils::TryParse(designID, designId)) { + const auto designId = GeneralUtils::TryParse(designID); + if (!designId) { LOG("Failed to parse designID %s", designID); continue; } - parts[designId]++; + parts[designId.value()]++; } currentBrick = currentBrick->NextSiblingElement(searchTerm.c_str()); diff --git a/dGame/dInventory/ItemSet.cpp b/dGame/dInventory/ItemSet.cpp index 54db9e9c..1d086786 100644 --- a/dGame/dInventory/ItemSet.cpp +++ b/dGame/dInventory/ItemSet.cpp @@ -87,10 +87,8 @@ ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) { m_Items = {}; while (std::getline(stream, token, ',')) { - int32_t value; - if (GeneralUtils::TryParse(token, value)) { - m_Items.push_back(value); - } + const auto validToken = GeneralUtils::TryParse(token); + if (validToken) m_Items.push_back(validToken.value()); } m_Equipped = {}; diff --git a/dGame/dMission/MissionTask.cpp b/dGame/dMission/MissionTask.cpp index 604276ec..2fe9bc9f 100644 --- a/dGame/dMission/MissionTask.cpp +++ b/dGame/dMission/MissionTask.cpp @@ -27,19 +27,15 @@ MissionTask::MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask) std::string token; while (std::getline(stream, token, ',')) { - uint32_t parameter; - if (GeneralUtils::TryParse(token, parameter)) { - parameters.push_back(parameter); - } + const auto parameter = GeneralUtils::TryParse(token); + if (parameter) parameters.push_back(parameter.value()); } stream = std::istringstream(info->targetGroup); while (std::getline(stream, token, ',')) { - uint32_t parameter; - if (GeneralUtils::TryParse(token, parameter)) { - targets.push_back(parameter); - } + const auto parameter = GeneralUtils::TryParse(token); + if (parameter) targets.push_back(parameter.value()); } } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp index cc817cd7..0aad74dd 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp @@ -5,7 +5,7 @@ #include "dCommonVars.h" BehaviorMessageBase::BehaviorMessageBase(AMFArrayValue* arguments) { - behaviorId = GetBehaviorIdFromArgument(arguments); + this->behaviorId = GetBehaviorIdFromArgument(arguments); } int32_t BehaviorMessageBase::GetBehaviorIdFromArgument(AMFArrayValue* arguments) { @@ -13,12 +13,13 @@ int32_t BehaviorMessageBase::GetBehaviorIdFromArgument(AMFArrayValue* arguments) auto* behaviorIDValue = arguments->Get(key); if (behaviorIDValue && behaviorIDValue->GetValueType() == eAmf::String) { - GeneralUtils::TryParse(behaviorIDValue->GetValue(), behaviorId); + this->behaviorId = + GeneralUtils::TryParse(behaviorIDValue->GetValue()).value_or(this->behaviorId); } else if (arguments->Get(key) && arguments->Get(key)->GetValueType() != eAmf::Undefined) { throw std::invalid_argument("Unable to find behavior ID"); } - return behaviorId; + return this->behaviorId; } int32_t BehaviorMessageBase::GetActionIndexFromArgument(AMFArrayValue* arguments, const std::string& keyName) { diff --git a/dGame/dUtilities/Preconditions.cpp b/dGame/dUtilities/Preconditions.cpp index 12059b5b..bd855962 100644 --- a/dGame/dUtilities/Preconditions.cpp +++ b/dGame/dUtilities/Preconditions.cpp @@ -40,10 +40,8 @@ Precondition::Precondition(const uint32_t condition) { std::string token; while (std::getline(stream, token, ',')) { - uint32_t value; - if (GeneralUtils::TryParse(token, value)) { - this->values.push_back(value); - } + const auto validToken = GeneralUtils::TryParse(token); + if (validToken) this->values.push_back(validToken.value()); } } diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index ef12c396..169426ab 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -113,13 +113,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if ((chatCommand == "setgmlevel" || chatCommand == "makegm" || chatCommand == "gmlevel") && user->GetMaxGMLevel() > eGameMasterLevel::CIVILIAN) { if (args.size() != 1) return; - uint32_t level_intermed = 0; + const auto level_intermed = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], level_intermed)) { + if (!level_intermed) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid gm level."); return; } - eGameMasterLevel level = static_cast(level_intermed); + eGameMasterLevel level = static_cast(level_intermed.value()); #ifndef DEVELOPER_SERVER if (user->GetMaxGMLevel() == eGameMasterLevel::JUNIOR_DEVELOPER) { @@ -378,26 +378,27 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "resetmission" && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - uint32_t missionId; - if (!GeneralUtils::TryParse(args[0], missionId)) { + const auto missionId = GeneralUtils::TryParse(args[0]); + if (!missionId) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission ID."); return; } auto* missionComponent = entity->GetComponent(); if (!missionComponent) return; - missionComponent->ResetMission(missionId); + missionComponent->ResetMission(missionId.value()); } // Log command to database Database::Get()->InsertSlashCommandUsage(entity->GetObjectID(), chatCommand); if (chatCommand == "setminifig" && args.size() == 2 && entity->GetGMLevel() >= eGameMasterLevel::FORUM_MODERATOR) { // could break characters so only allow if GM > 0 - int32_t minifigItemId; - if (!GeneralUtils::TryParse(args[1], minifigItemId)) { + const auto minifigItemIdExists = GeneralUtils::TryParse(args[1]); + if (!minifigItemIdExists) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid Minifig Item Id ID."); return; } + const int32_t minifigItemId = minifigItemIdExists.value(); Game::entityManager->DestructEntity(entity, sysAddr); auto* charComp = entity->GetComponent(); std::string lowerName = args[0]; @@ -457,14 +458,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "unlock-emote" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - int32_t emoteID; + const auto emoteID = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], emoteID)) { + if (!emoteID) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid emote ID."); return; } - entity->GetCharacter()->UnlockEmote(emoteID); + entity->GetCharacter()->UnlockEmote(emoteID.value()); } if (chatCommand == "force-save" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { @@ -486,19 +487,19 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "speedboost" && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - float boost; - - if (!GeneralUtils::TryParse(args[0], boost)) { + const auto boostOptional = GeneralUtils::TryParse(args[0]); + if (!boostOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid boost."); return; } + const float boost = boostOptional.value(); auto* controllablePhysicsComponent = entity->GetComponent(); if (!controllablePhysicsComponent) return; controllablePhysicsComponent->SetSpeedMultiplier(boost); - // speedboost possesables + // speedboost possessables auto possessor = entity->GetComponent(); if (possessor) { auto possessedID = possessor->GetPossessable(); @@ -527,14 +528,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "setcontrolscheme" && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - uint32_t scheme; + const auto scheme = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], scheme)) { + if (!scheme) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid control scheme."); return; } - GameMessages::SendSetPlayerControlScheme(entity, static_cast(scheme)); + GameMessages::SendSetPlayerControlScheme(entity, static_cast(scheme.value())); ChatPackets::SendSystemMessage(sysAddr, u"Switched control scheme."); return; @@ -574,29 +575,28 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if ((chatCommand == "setinventorysize" || chatCommand == "setinvsize") && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { - uint32_t size; - - if (!GeneralUtils::TryParse(args.at(0), size)) { + const auto sizeOptional = GeneralUtils::TryParse(args[0]); + if (!sizeOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid size."); return; } + const uint32_t size = sizeOptional.value(); eInventoryType selectedInventory = eInventoryType::ITEMS; // a possible inventory was provided if we got more than 1 argument if (args.size() >= 2) { - selectedInventory = eInventoryType::INVALID; - if (!GeneralUtils::TryParse(args.at(1), selectedInventory)) { + selectedInventory = GeneralUtils::TryParse(args.at(1)).value_or(eInventoryType::INVALID); + if (selectedInventory == eInventoryType::INVALID) { + ChatPackets::SendSystemMessage(sysAddr, u"Invalid inventory."); + return; + } else { // In this case, we treat the input as a string and try to find it in the reflection list std::transform(args.at(1).begin(), args.at(1).end(), args.at(1).begin(), ::toupper); for (uint32_t index = 0; index < NUMBER_OF_INVENTORIES; index++) { if (std::string_view(args.at(1)) == std::string_view(InventoryType::InventoryTypeToString(static_cast(index)))) selectedInventory = static_cast(index); } } - if (selectedInventory == eInventoryType::INVALID) { - ChatPackets::SendSystemMessage(sysAddr, u"Invalid inventory."); - return; - } ChatPackets::SendSystemMessage(sysAddr, u"Setting inventory " + GeneralUtils::ASCIIToUTF16(args.at(1)) + @@ -643,48 +643,48 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "addmission" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() == 0) return; - uint32_t missionID; + const auto missionID = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], missionID)) { + if (!missionID) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission id."); return; } auto comp = static_cast(entity->GetComponent(eReplicaComponentType::MISSION)); - if (comp) comp->AcceptMission(missionID, true); + if (comp) comp->AcceptMission(missionID.value(), true); return; } if (chatCommand == "completemission" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() == 0) return; - uint32_t missionID; + const auto missionID = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], missionID)) { + if (!missionID) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission id."); return; } auto comp = static_cast(entity->GetComponent(eReplicaComponentType::MISSION)); - if (comp) comp->CompleteMission(missionID, true); + if (comp) comp->CompleteMission(missionID.value(), true); return; } if (chatCommand == "setflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - int32_t flagId; + const auto flagId = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], flagId)) { + if (!flagId) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } - entity->GetCharacter()->SetPlayerFlag(flagId, true); + entity->GetCharacter()->SetPlayerFlag(flagId.value(), true); } if (chatCommand == "setflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 2) { - int32_t flagId; - std::string onOffFlag = args[0]; - if (!GeneralUtils::TryParse(args[1], flagId)) { + const auto flagId = GeneralUtils::TryParse(args.at(1)); + std::string onOffFlag = args.at(0); + if (!flagId) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } @@ -692,28 +692,26 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag type."); return; } - entity->GetCharacter()->SetPlayerFlag(flagId, onOffFlag == "on"); + entity->GetCharacter()->SetPlayerFlag(flagId.value(), onOffFlag == "on"); } if (chatCommand == "clearflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - int32_t flagId; + const auto flagId = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], flagId)) { + if (!flagId) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } - entity->GetCharacter()->SetPlayerFlag(flagId, false); + entity->GetCharacter()->SetPlayerFlag(flagId.value(), false); } if (chatCommand == "playeffect" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 3) { - int32_t effectID = 0; + const auto effectID = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], effectID)) { - return; - } + if (!effectID) return; // FIXME: use fallible ASCIIToUTF16 conversion, because non-ascii isn't valid anyway - GameMessages::SendPlayFXEffect(entity->GetObjectID(), effectID, GeneralUtils::ASCIIToUTF16(args[1]), args[2]); + GameMessages::SendPlayFXEffect(entity->GetObjectID(), effectID.value(), GeneralUtils::ASCIIToUTF16(args.at(1)), args.at(2)); } if (chatCommand == "stopeffect" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { @@ -775,34 +773,32 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "gmadditem" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() == 1) { - uint32_t itemLOT; + const auto itemLOT = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], itemLOT)) { + if (!itemLOT) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item LOT."); return; } InventoryComponent* inventory = static_cast(entity->GetComponent(eReplicaComponentType::INVENTORY)); - inventory->AddItem(itemLOT, 1, eLootSourceType::MODERATION); + inventory->AddItem(itemLOT.value(), 1, eLootSourceType::MODERATION); } else if (args.size() == 2) { - uint32_t itemLOT; - - if (!GeneralUtils::TryParse(args[0], itemLOT)) { + const auto itemLOT = GeneralUtils::TryParse(args.at(0)); + if (!itemLOT) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item LOT."); return; } - uint32_t count; - - if (!GeneralUtils::TryParse(args[1], count)) { + const auto count = GeneralUtils::TryParse(args.at(1)); + if (!count) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item count."); return; } InventoryComponent* inventory = static_cast(entity->GetComponent(eReplicaComponentType::INVENTORY)); - inventory->AddItem(itemLOT, count, eLootSourceType::MODERATION); + inventory->AddItem(itemLOT.value(), count.value(), eLootSourceType::MODERATION); } else { ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /gmadditem "); } @@ -822,9 +818,9 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit receiverID = playerInfo->id; - LOT lot; + const auto lot = GeneralUtils::TryParse(args.at(1)); - if (!GeneralUtils::TryParse(args[1], lot)) { + if (!lot) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item lot."); return; } @@ -837,7 +833,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit mailInsert.subject = "Lost item"; mailInsert.body = "This is a replacement item for one you lost."; mailInsert.itemID = LWOOBJID_EMPTY; - mailInsert.itemLOT = lot; + mailInsert.itemLOT = lot.value(); mailInsert.itemSubkey = LWOOBJID_EMPTY; mailInsert.itemCount = 1; Database::Get()->InsertNewMail(mailInsert); @@ -871,46 +867,47 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit NiPoint3 pos{}; if (args.size() == 3) { - float x, y, z; - - if (!GeneralUtils::TryParse(args[0], x)) { + const auto x = GeneralUtils::TryParse(args.at(0)); + if (!x) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid x."); return; } - if (!GeneralUtils::TryParse(args[1], y)) { + const auto y = GeneralUtils::TryParse(args.at(1)); + if (!y) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid y."); return; } - if (!GeneralUtils::TryParse(args[2], z)) { + const auto z = GeneralUtils::TryParse(args.at(2)); + if (!z) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid z."); return; } - pos.SetX(x); - pos.SetY(y); - pos.SetZ(z); + pos.SetX(x.value()); + pos.SetY(y.value()); + pos.SetZ(z.value()); LOG("Teleporting objectID: %llu to %f, %f, %f", entity->GetObjectID(), pos.x, pos.y, pos.z); GameMessages::SendTeleport(entity->GetObjectID(), pos, NiQuaternion(), sysAddr); } else if (args.size() == 2) { - float x, z; - - if (!GeneralUtils::TryParse(args[0], x)) { + const auto x = GeneralUtils::TryParse(args.at(0)); + if (!x) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid x."); return; } - if (!GeneralUtils::TryParse(args[1], z)) { + const auto z = GeneralUtils::TryParse(args.at(1)); + if (!z) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid z."); return; } - pos.SetX(x); + pos.SetX(x.value()); pos.SetY(0.0f); - pos.SetZ(z); + pos.SetZ(z.value()); LOG("Teleporting objectID: %llu to X: %f, Z: %f", entity->GetObjectID(), pos.x, pos.z); GameMessages::SendTeleport(entity->GetObjectID(), pos, NiQuaternion(), sysAddr); @@ -970,10 +967,10 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit float speedScale = 1.0f; if (args.size() >= 1) { - float tempScaleStore; + const auto tempScaleStore = GeneralUtils::TryParse(args.at(0)); - if (GeneralUtils::TryParse(args[0], tempScaleStore)) { - speedScale = tempScaleStore; + if (tempScaleStore) { + speedScale = tempScaleStore.value(); } else { ChatPackets::SendSystemMessage(sysAddr, u"Failed to parse speed scale argument."); } @@ -1025,16 +1022,17 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit time_t expire = 1; // Default to indefinate mute if (args.size() >= 2) { - uint32_t days = 0; - uint32_t hours = 0; - if (!GeneralUtils::TryParse(args[1], days)) { + const auto days = GeneralUtils::TryParse(args[1]); + if (!days) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid days."); return; } + std::optional hours; if (args.size() >= 3) { - if (!GeneralUtils::TryParse(args[2], hours)) { + hours = GeneralUtils::TryParse(args[2]); + if (!hours) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid hours."); return; @@ -1042,8 +1040,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } expire = time(NULL); - expire += 24 * 60 * 60 * days; - expire += 60 * 60 * hours; + expire += 24 * 60 * 60 * days.value(); + expire += 60 * 60 * hours.value_or(0); } if (accountId != 0) Database::Get()->UpdateAccountUnmuteTime(accountId, expire); @@ -1143,14 +1141,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "startcelebration" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - int32_t celebration; + const auto celebration = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], celebration)) { + if (!celebration) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid celebration."); return; } - GameMessages::SendStartCelebrationEffect(entity, entity->GetSystemAddress(), celebration); + GameMessages::SendStartCelebrationEffect(entity, entity->GetSystemAddress(), celebration.value()); } if (chatCommand == "buffmed" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { @@ -1204,15 +1202,15 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ControllablePhysicsComponent* comp = static_cast(entity->GetComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS)); if (!comp) return; - uint32_t lot; + const auto lot = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], lot)) { + if (!lot) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid lot."); return; } EntityInfo info; - info.lot = lot; + info.lot = lot.value(); info.pos = comp->GetPosition(); info.rot = comp->GetRotation(); info.spawner = nullptr; @@ -1233,28 +1231,29 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto controllablePhysicsComponent = entity->GetComponent(); if (!controllablePhysicsComponent) return; - LOT lot{}; - uint32_t numberToSpawn{}; - float radiusToSpawnWithin{}; - - if (!GeneralUtils::TryParse(args[0], lot)) { + const auto lot = GeneralUtils::TryParse(args[0]); + if (!lot) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid lot."); return; } - if (!GeneralUtils::TryParse(args[1], numberToSpawn) && numberToSpawn > 0) { + const auto numberToSpawnOptional = GeneralUtils::TryParse(args[1]); + if (!numberToSpawnOptional && numberToSpawnOptional.value() > 0) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid number of enemies to spawn."); return; } + uint32_t numberToSpawn = numberToSpawnOptional.value(); // Must spawn within a radius of at least 0.0f - if (!GeneralUtils::TryParse(args[2], radiusToSpawnWithin) && radiusToSpawnWithin < 0.0f) { + const auto radiusToSpawnWithinOptional = GeneralUtils::TryParse(args[2]); + if (!radiusToSpawnWithinOptional && radiusToSpawnWithinOptional.value() < 0.0f) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid radius to spawn within."); return; } + const float radiusToSpawnWithin = radiusToSpawnWithinOptional.value(); EntityInfo info; - info.lot = lot; + info.lot = lot.value(); info.spawner = nullptr; info.spawnerID = entity->GetObjectID(); info.spawnerNodeID = 0; @@ -1281,12 +1280,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if ((chatCommand == "giveuscore") && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - int32_t uscore; - - if (!GeneralUtils::TryParse(args[0], uscore)) { + const auto uscoreOptional = GeneralUtils::TryParse(args[0]); + if (!uscoreOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid uscore."); return; } + const int32_t uscore = uscoreOptional.value(); CharacterComponent* character = entity->GetComponent(); if (character) character->SetUScore(character->GetUScore() + uscore); @@ -1294,9 +1293,9 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit eLootSourceType lootType = eLootSourceType::MODERATION; - int32_t type; - if (args.size() >= 2 && GeneralUtils::TryParse(args[1], type)) { - lootType = static_cast(type); + if (args.size() >= 2) { + const auto type = GeneralUtils::TryParse(args[1]); + lootType = type.value_or(lootType); } GameMessages::SendModifyLEGOScore(entity, entity->GetSystemAddress(), uscore, lootType); @@ -1322,14 +1321,15 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit entity = requestedPlayer->GetOwner(); } - uint32_t requestedLevel; + const auto requestedLevelOptional = GeneralUtils::TryParse(args[0]); uint32_t oldLevel; - // first check the level is valid - if (!GeneralUtils::TryParse(args[0], requestedLevel)) { + // first check the level is valid + if (!requestedLevelOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid level."); return; } + uint32_t requestedLevel = requestedLevelOptional.value(); // query to set our uscore to the correct value for this level auto characterComponent = entity->GetComponent(); @@ -1402,27 +1402,27 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if ((chatCommand == "freemoney" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) && args.size() == 1) { - int64_t money; + const auto money = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], money)) { + if (!money) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid money."); return; } auto* ch = entity->GetCharacter(); - ch->SetCoins(ch->GetCoins() + money, eLootSourceType::MODERATION); + ch->SetCoins(ch->GetCoins() + money.value(), eLootSourceType::MODERATION); } if ((chatCommand == "setcurrency") && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - int32_t money; + const auto money = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], money)) { + if (!money) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid money."); return; } auto* ch = entity->GetCharacter(); - ch->SetCoins(money, eLootSourceType::MODERATION); + ch->SetCoins(money.value(), eLootSourceType::MODERATION); } // Allow for this on even while not a GM, as it sometimes toggles incorrrectly. @@ -1435,17 +1435,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "gmimmune" && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto* destroyableComponent = entity->GetComponent(); - int32_t state = false; + const auto state = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], state)) { + if (!state) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid state."); return; } - if (destroyableComponent != nullptr) { - destroyableComponent->SetIsGMImmune(state); - } - + if (destroyableComponent) destroyableComponent->SetIsGMImmune(state.value()); return; } @@ -1453,53 +1450,47 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "attackimmune" && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto* destroyableComponent = entity->GetComponent(); - int32_t state = false; + const auto state = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], state)) { + if (!state) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid state."); return; } - if (destroyableComponent != nullptr) { - destroyableComponent->SetIsImmune(state); - } - + if (destroyableComponent) destroyableComponent->SetIsImmune(state.value()); return; } if (chatCommand == "buff" && args.size() >= 2 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto* buffComponent = entity->GetComponent(); - int32_t id = 0; - int32_t duration = 0; - - if (!GeneralUtils::TryParse(args[0], id)) { + const auto id = GeneralUtils::TryParse(args[0]); + if (!id) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid buff id."); return; } - if (!GeneralUtils::TryParse(args[1], duration)) { + const auto duration = GeneralUtils::TryParse(args[1]); + if (!duration) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid buff duration."); return; } - if (buffComponent != nullptr) { - buffComponent->ApplyBuff(id, duration, entity->GetObjectID()); - } - + if (buffComponent) buffComponent->ApplyBuff(id.value(), duration.value(), entity->GetObjectID()); return; } if ((chatCommand == "testmap" && args.size() >= 1) && entity->GetGMLevel() >= eGameMasterLevel::FORUM_MODERATOR) { ChatPackets::SendSystemMessage(sysAddr, u"Requesting map change..."); - uint32_t reqZone; LWOCLONEID cloneId = 0; bool force = false; - if (!GeneralUtils::TryParse(args[0], reqZone)) { + const auto reqZoneOptional = GeneralUtils::TryParse(args[0]); + if (!reqZoneOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid zone."); return; } + const LWOMAPID reqZone = reqZoneOptional.value(); if (args.size() > 1) { auto index = 1; @@ -1510,9 +1501,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit force = true; } - if (args.size() > index && !GeneralUtils::TryParse(args[index], cloneId)) { - ChatPackets::SendSystemMessage(sysAddr, u"Invalid clone id."); - return; + if (args.size() > index) { + const auto cloneIdOptional = GeneralUtils::TryParse(args[index]); + if (!cloneIdOptional) { + ChatPackets::SendSystemMessage(sysAddr, u"Invalid clone id."); + return; + } + cloneId = cloneIdOptional.value(); } } @@ -1550,23 +1545,21 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "createprivate" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 3) { - uint32_t zone; - - if (!GeneralUtils::TryParse(args[0], zone)) { + const auto zone = GeneralUtils::TryParse(args[0]); + if (!zone) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid zone."); return; } - uint32_t clone; - - if (!GeneralUtils::TryParse(args[1], clone)) { + const auto clone = GeneralUtils::TryParse(args[1]); + if (!clone) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid clone."); return; } const auto& password = args[2]; - ZoneInstanceManager::Instance()->CreatePrivateZone(Game::server, zone, clone, password); + ZoneInstanceManager::Instance()->CreatePrivateZone(Game::server, zone.value(), clone.value(), password); ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16("Sent request for private zone with password: " + password)); @@ -1593,14 +1586,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (args.size() >= 1) { - float time; + const auto time = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], time)) { + if (!time) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid boost time."); return; } else { GameMessages::SendVehicleAddPassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - entity->AddCallbackTimer(time, [vehicle]() { + entity->AddCallbackTimer(time.value(), [vehicle]() { if (!vehicle) return; GameMessages::SendVehicleRemovePassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); }); @@ -1676,20 +1669,19 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "reforge" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 2) { - LOT baseItem; - LOT reforgedItem; + const auto baseItem = GeneralUtils::TryParse(args[0]); + if (!baseItem) return; - if (!GeneralUtils::TryParse(args[0], baseItem)) return; - if (!GeneralUtils::TryParse(args[1], reforgedItem)) return; + const auto reforgedItem = GeneralUtils::TryParse(args[1]); + if (!reforgedItem) return; auto* inventoryComponent = entity->GetComponent(); - - if (inventoryComponent == nullptr) return; + if (!inventoryComponent) return; std::vector data{}; - data.push_back(new LDFData(u"reforgedLOT", reforgedItem)); + data.push_back(new LDFData(u"reforgedLOT", reforgedItem.value())); - inventoryComponent->AddItem(baseItem, 1, eLootSourceType::MODERATION, eInventoryType::INVALID, data); + inventoryComponent->AddItem(baseItem.value(), 1, eLootSourceType::MODERATION, eInventoryType::INVALID, data); } if (chatCommand == "crash" && entity->GetGMLevel() >= eGameMasterLevel::OPERATOR) { @@ -1743,8 +1735,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit VanityUtilities::SpawnVanity(); dpWorld::Reload(); auto entities = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY); - for (auto entity : entities) { - auto* scriptedActivityComponent = entity->GetComponent(); + for (const auto* const entity : entities) { + auto* const scriptedActivityComponent = entity->GetComponent(); if (!scriptedActivityComponent) continue; scriptedActivityComponent->ReloadConfig(); @@ -1755,19 +1747,20 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "rollloot" && entity->GetGMLevel() >= eGameMasterLevel::OPERATOR && args.size() >= 3) { - uint32_t lootMatrixIndex = 0; - uint32_t targetLot = 0; - uint32_t loops = 1; + const auto lootMatrixIndex = GeneralUtils::TryParse(args[0]); + if (!lootMatrixIndex) return; - if (!GeneralUtils::TryParse(args[0], lootMatrixIndex)) return; - if (!GeneralUtils::TryParse(args[1], targetLot)) return; - if (!GeneralUtils::TryParse(args[2], loops)) return; + const auto targetLot = GeneralUtils::TryParse(args[1]); + if (!targetLot) return; + + const auto loops = GeneralUtils::TryParse(args[2]); + if (!loops) return; uint64_t totalRuns = 0; for (uint32_t i = 0; i < loops; i++) { while (true) { - auto lootRoll = Loot::RollLootMatrix(lootMatrixIndex); + auto lootRoll = Loot::RollLootMatrix(lootMatrixIndex.value()); totalRuns += 1; bool doBreak = false; for (const auto& kv : lootRoll) { @@ -1780,26 +1773,30 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } std::u16string message = u"Ran loot drops looking for " - + GeneralUtils::to_u16string(targetLot) + + GeneralUtils::to_u16string(targetLot.value()) + u", " - + GeneralUtils::to_u16string(loops) + + GeneralUtils::to_u16string(loops.value()) + u" times. It ran " + GeneralUtils::to_u16string(totalRuns) + u" times. Averaging out at " - + GeneralUtils::to_u16string(static_cast(totalRuns) / loops); + + GeneralUtils::to_u16string(static_cast(totalRuns) / loops.value()); ChatPackets::SendSystemMessage(sysAddr, message); } if (chatCommand == "deleteinven" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { eInventoryType inventoryType = eInventoryType::INVALID; - if (!GeneralUtils::TryParse(args[0], inventoryType)) { + + const auto inventoryTypeOptional = GeneralUtils::TryParse(args[0]); + if (!inventoryTypeOptional) { // In this case, we treat the input as a string and try to find it in the reflection list std::transform(args[0].begin(), args[0].end(), args[0].begin(), ::toupper); LOG("looking for inventory %s", args[0].c_str()); for (uint32_t index = 0; index < NUMBER_OF_INVENTORIES; index++) { if (std::string_view(args[0]) == std::string_view(InventoryType::InventoryTypeToString(static_cast(index)))) inventoryType = static_cast(index); } + } else { + inventoryType = inventoryTypeOptional.value(); } if (inventoryType == eInventoryType::INVALID || inventoryType >= NUMBER_OF_INVENTORIES) { @@ -1821,32 +1818,32 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "castskill" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { auto* skillComponent = entity->GetComponent(); if (skillComponent) { - uint32_t skillId; + const auto skillId = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], skillId)) { + if (!skillId) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting skill ID."); return; } else { - skillComponent->CastSkill(skillId, entity->GetObjectID(), entity->GetObjectID()); + skillComponent->CastSkill(skillId.value(), entity->GetObjectID(), entity->GetObjectID()); ChatPackets::SendSystemMessage(sysAddr, u"Cast skill"); } } } if (chatCommand == "setskillslot" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 2) { - uint32_t skillId; - int slot; - auto* inventoryComponent = entity->GetComponent(); + auto* const inventoryComponent = entity->GetComponent(); if (inventoryComponent) { - if (!GeneralUtils::TryParse(args[0], slot)) { + const auto slot = GeneralUtils::TryParse(args[0]); + if (!slot) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting slot."); return; } else { - if (!GeneralUtils::TryParse(args[1], skillId)) { + const auto skillId = GeneralUtils::TryParse(args[1]); + if (!skillId) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting skill."); return; } else { - if (inventoryComponent->SetSkill(slot, skillId)) ChatPackets::SendSystemMessage(sysAddr, u"Set skill to slot successfully"); + if (inventoryComponent->SetSkill(slot.value(), skillId.value())) ChatPackets::SendSystemMessage(sysAddr, u"Set skill to slot successfully"); else ChatPackets::SendSystemMessage(sysAddr, u"Set skill to slot failed"); } } @@ -1856,13 +1853,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "setfaction" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { auto* destroyableComponent = entity->GetComponent(); if (destroyableComponent) { - int32_t faction; + const auto faction = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], faction)) { + if (!faction) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting faction."); return; } else { - destroyableComponent->SetFaction(faction); + destroyableComponent->SetFaction(faction.value()); ChatPackets::SendSystemMessage(sysAddr, u"Set faction and updated enemies list"); } } @@ -1871,13 +1868,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "addfaction" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { auto* destroyableComponent = entity->GetComponent(); if (destroyableComponent) { - int32_t faction; + const auto faction = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], faction)) { + if (!faction) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting faction."); return; } else { - destroyableComponent->AddFaction(faction); + destroyableComponent->AddFaction(faction.value()); ChatPackets::SendSystemMessage(sysAddr, u"Added faction and updated enemies list"); } } @@ -1908,13 +1905,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "inspect" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { Entity* closest = nullptr; - eReplicaComponentType component; - std::u16string ldf; bool isLDF = false; - if (!GeneralUtils::TryParse(args[0], component)) { + auto component = GeneralUtils::TryParse(args[0]); + if (!component) { component = eReplicaComponentType::INVALID; ldf = GeneralUtils::UTF8ToUTF16(args[0]); @@ -1926,7 +1922,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto closestDistance = 0.0f; - const auto candidates = Game::entityManager->GetEntitiesByComponent(component); + const auto candidates = Game::entityManager->GetEntitiesByComponent(component.value()); for (auto* candidate : candidates) { if (candidate->GetLOT() == 1 || candidate->GetLOT() == 8092) { @@ -1937,7 +1933,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit continue; } - if (closest == nullptr) { + if (!closest) { closest = candidate; closestDistance = NiPoint3::Distance(candidate->GetPosition(), reference); @@ -1954,9 +1950,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (closest == nullptr) { - return; - } + if (!closest) return; Game::entityManager->SerializeEntity(closest); @@ -1982,20 +1976,18 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (args.size() >= 2) { if (args[1] == "-m" && args.size() >= 3) { - auto* movingPlatformComponent = closest->GetComponent(); + auto* const movingPlatformComponent = closest->GetComponent(); - int32_t value = 0; + const auto mValue = GeneralUtils::TryParse(args[2]); - if (movingPlatformComponent == nullptr || !GeneralUtils::TryParse(args[2], value)) { - return; - } + if (!movingPlatformComponent || !mValue) return; movingPlatformComponent->SetSerialized(true); - if (value == -1) { + if (mValue == -1) { movingPlatformComponent->StopPathing(); } else { - movingPlatformComponent->GotoWaypoint(value); + movingPlatformComponent->GotoWaypoint(mValue.value()); } Game::entityManager->SerializeEntity(closest); @@ -2036,13 +2028,11 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (args.size() >= 3) { - int32_t faction; - if (!GeneralUtils::TryParse(args[2], faction)) { - return; - } + const auto faction = GeneralUtils::TryParse(args[2]); + if (!faction) return; destuctable->SetFaction(-1); - destuctable->AddFaction(faction, true); + destuctable->AddFaction(faction.value(), true); } } else if (args[1] == "-cf") { auto* destuctable = entity->GetComponent(); diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index a46ed81a..9ae9930c 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -17,7 +17,8 @@ InstanceManager::InstanceManager(Logger* logger, const std::string& externalIP) { mLogger = logger; mExternalIP = externalIP; - GeneralUtils::TryParse(Game::config->GetValue("world_port_start"), m_LastPort); + m_LastPort = + GeneralUtils::TryParse(Game::config->GetValue("world_port_start")).value_or(m_LastPort); m_LastInstanceID = LWOINSTANCEID_INVALID; } diff --git a/dMasterServer/InstanceManager.h b/dMasterServer/InstanceManager.h index b9f1ec5a..1fc4af43 100644 --- a/dMasterServer/InstanceManager.h +++ b/dMasterServer/InstanceManager.h @@ -134,7 +134,7 @@ private: Logger* mLogger; std::string mExternalIP; std::vector m_Instances; - unsigned short m_LastPort = 3000; + uint16_t m_LastPort = 3000; LWOINSTANCEID m_LastInstanceID; /** diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 749b4130..1fade06e 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -89,9 +89,8 @@ int main(int argc, char** argv) { if (!dConfig::Exists("worldconfig.ini")) LOG("Could not find worldconfig.ini, using default settings"); - uint32_t clientNetVersion = 171022; const auto clientNetVersionString = Game::config->GetValue("client_net_version"); - if (!clientNetVersionString.empty()) GeneralUtils::TryParse(clientNetVersionString, clientNetVersion); + const uint32_t clientNetVersion = GeneralUtils::TryParse(clientNetVersionString).value_or(171022); LOG("Using net version %i", clientNetVersion); diff --git a/dNet/AuthPackets.cpp b/dNet/AuthPackets.cpp index 9982f89e..25ccc902 100644 --- a/dNet/AuthPackets.cpp +++ b/dNet/AuthPackets.cpp @@ -8,6 +8,7 @@ #include "ZoneInstanceManager.h" #include "MD5.h" #include "GeneralUtils.h" +#include "ClientVersion.h" #include @@ -38,10 +39,9 @@ void AuthPackets::LoadClaimCodes() { auto rcstring = Game::config->GetValue("rewardcodes"); auto codestrings = GeneralUtils::SplitString(rcstring, ','); for(auto const &codestring: codestrings){ - uint32_t code = -1; - if(GeneralUtils::TryParse(codestring, code) && code != -1){ - claimCodes.push_back(code); - } + const auto code = GeneralUtils::TryParse(codestring); + + if (code && code.value() != -1) claimCodes.push_back(code.value()); } } @@ -73,9 +73,8 @@ void AuthPackets::SendHandshake(dServer* server, const SystemAddress& sysAddr, c RakNet::BitStream bitStream; BitStreamUtils::WriteHeader(bitStream, eConnectionType::SERVER, eServerMessageType::VERSION_CONFIRM); - uint32_t clientNetVersion = 171022; const auto clientNetVersionString = Game::config->GetValue("client_net_version"); - if (!clientNetVersionString.empty()) GeneralUtils::TryParse(clientNetVersionString, clientNetVersion); + const uint32_t clientNetVersion = GeneralUtils::TryParse(clientNetVersionString).value_or(171022); bitStream.Write(clientNetVersion); bitStream.Write(861228100); @@ -242,12 +241,12 @@ void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAdd loginResponse.Write(LUString(Game::config->GetValue("event_7"))); loginResponse.Write(LUString(Game::config->GetValue("event_8"))); - uint16_t version_major = 1; - uint16_t version_current = 10; - uint16_t version_minor = 64; - GeneralUtils::TryParse(Game::config->GetValue("version_major"), version_major); - GeneralUtils::TryParse(Game::config->GetValue("version_current"), version_current); - GeneralUtils::TryParse(Game::config->GetValue("version_minor"), version_minor); + const uint16_t version_major = + GeneralUtils::TryParse(Game::config->GetValue("version_major")).value_or(ClientVersion::major); + const uint16_t version_current = + GeneralUtils::TryParse(Game::config->GetValue("version_current")).value_or(ClientVersion::current); + const uint16_t version_minor = + GeneralUtils::TryParse(Game::config->GetValue("version_minor")).value_or(ClientVersion::minor); loginResponse.Write(version_major); loginResponse.Write(version_current); diff --git a/dPhysics/dpWorld.cpp b/dPhysics/dpWorld.cpp index 4ed54858..c9bc742a 100644 --- a/dPhysics/dpWorld.cpp +++ b/dPhysics/dpWorld.cpp @@ -26,9 +26,15 @@ namespace { void dpWorld::Initialize(unsigned int zoneID, bool generateNewNavMesh) { const auto physSpTilecount = Game::config->GetValue("phys_sp_tilecount"); - if (!physSpTilecount.empty()) GeneralUtils::TryParse(physSpTilecount, phys_sp_tilecount); + if (!physSpTilecount.empty()) { + phys_sp_tilecount = GeneralUtils::TryParse(physSpTilecount).value_or(phys_sp_tilecount); + } + const auto physSpTilesize = Game::config->GetValue("phys_sp_tilesize"); - if (!physSpTilesize.empty()) GeneralUtils::TryParse(physSpTilesize, phys_sp_tilesize); + if (!physSpTilesize.empty()) { + phys_sp_tilesize = GeneralUtils::TryParse(physSpTilesize).value_or(phys_sp_tilesize); + } + const auto physSpatialPartitioning = Game::config->GetValue("phys_spatial_partitioning"); if (!physSpatialPartitioning.empty()) phys_spatial_partitioning = physSpatialPartitioning == "1"; diff --git a/dScripts/02_server/Map/AM/AmDropshipComputer.cpp b/dScripts/02_server/Map/AM/AmDropshipComputer.cpp index 60b750cf..357187ef 100644 --- a/dScripts/02_server/Map/AM/AmDropshipComputer.cpp +++ b/dScripts/02_server/Map/AM/AmDropshipComputer.cpp @@ -33,14 +33,12 @@ void AmDropshipComputer::OnUse(Entity* self, Entity* user) { void AmDropshipComputer::OnDie(Entity* self, Entity* killer) { const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - int32_t pipeNum = 0; - if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { - return; - } + const auto pipeNum = GeneralUtils::TryParse(myGroup.substr(10, 1)); + if (!pipeNum) return; const auto pipeGroup = myGroup.substr(0, 10); - const auto nextPipeNum = pipeNum + 1; + const auto nextPipeNum = pipeNum.value() + 1; const auto samePipeSpawners = Game::zoneManager->GetSpawnersByName(myGroup); @@ -70,11 +68,9 @@ void AmDropshipComputer::OnDie(Entity* self, Entity* killer) { } void AmDropshipComputer::OnTimerDone(Entity* self, std::string timerName) { - auto* quickBuildComponent = self->GetComponent(); + const auto* const quickBuildComponent = self->GetComponent(); - if (quickBuildComponent == nullptr) { - return; - } + if (!quickBuildComponent) return; if (timerName == "reset" && quickBuildComponent->GetState() == eQuickBuildState::OPEN) { self->Smash(self->GetObjectID(), eKillType::SILENT); diff --git a/dScripts/02_server/Map/AM/AmSkullkinTower.cpp b/dScripts/02_server/Map/AM/AmSkullkinTower.cpp index 0c0f7515..1eaad3c9 100644 --- a/dScripts/02_server/Map/AM/AmSkullkinTower.cpp +++ b/dScripts/02_server/Map/AM/AmSkullkinTower.cpp @@ -144,13 +144,10 @@ void AmSkullkinTower::OnChildRemoved(Entity* self, Entity* child) { ); for (const auto& mission : missions) { - int32_t missionID = 0; + const auto missionID = GeneralUtils::TryParse(mission); + if (!missionID) continue; - if (!GeneralUtils::TryParse(mission, missionID)) { - continue; - } - - missionIDs.push_back(missionID); + missionIDs.push_back(missionID.value()); } } diff --git a/dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp b/dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp index 3acc9063..82f1481a 100644 --- a/dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp +++ b/dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp @@ -12,12 +12,9 @@ void AmTemplateSkillVolume::OnSkillEventFired(Entity* self, Entity* caster, cons const auto missionIDs = GeneralUtils::SplitString(missionIDsVariable, '_'); for (const auto& missionIDStr : missionIDs) { - int32_t missionID = 0; + const auto missionID = GeneralUtils::TryParse(missionIDStr); + if (!missionID) continue; - if (!GeneralUtils::TryParse(missionIDStr, missionID)) { - continue; - } - - missionComponent->ForceProgressTaskType(missionID, 1, 1, false); + missionComponent->ForceProgressTaskType(missionID.value(), 1, 1, false); } } diff --git a/dScripts/ChooseYourDestinationNsToNt.cpp b/dScripts/ChooseYourDestinationNsToNt.cpp index f9ca0a79..b736883c 100644 --- a/dScripts/ChooseYourDestinationNsToNt.cpp +++ b/dScripts/ChooseYourDestinationNsToNt.cpp @@ -41,11 +41,9 @@ void ChooseYourDestinationNsToNt::SetDestination(Entity* self, Entity* player) { void ChooseYourDestinationNsToNt::BaseChoiceBoxRespond(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { if (button != -1) { const auto newMapStr = GeneralUtils::UTF16ToWTF8(buttonIdentifier).substr(7, -1); - - int32_t newMap = 0; - if (!GeneralUtils::TryParse(newMapStr, newMap)) { - return; - } + const auto newMap = GeneralUtils::TryParse(newMapStr); + + if (!newMap) return; std::u16string strText = u""; @@ -56,7 +54,7 @@ void ChooseYourDestinationNsToNt::BaseChoiceBoxRespond(Entity* self, Entity* sen } self->SetVar(u"teleportString", strText); - self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(newMap)); + self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(newMap.value())); GameMessages::SendDisplayMessageBox(sender->GetObjectID(), true, self->GetObjectID(), u"TransferBox", 0, strText, u"", sender->GetSystemAddress()); } else { diff --git a/dScripts/ai/FV/FvBrickPuzzleServer.cpp b/dScripts/ai/FV/FvBrickPuzzleServer.cpp index e1f1ac88..f8601e3f 100644 --- a/dScripts/ai/FV/FvBrickPuzzleServer.cpp +++ b/dScripts/ai/FV/FvBrickPuzzleServer.cpp @@ -7,10 +7,8 @@ void FvBrickPuzzleServer::OnStartup(Entity* self) { const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - int32_t pipeNum = 0; - if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { - return; - } + const auto pipeNum = GeneralUtils::TryParse(myGroup.substr(10, 1)); + if (!pipeNum) return; if (pipeNum != 1) { self->AddTimer("reset", 30); @@ -20,14 +18,12 @@ void FvBrickPuzzleServer::OnStartup(Entity* self) { void FvBrickPuzzleServer::OnDie(Entity* self, Entity* killer) { const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - int32_t pipeNum = 0; - if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { - return; - } + const auto pipeNum = GeneralUtils::TryParse(myGroup.substr(10, 1)); + if (!pipeNum) return; const auto pipeGroup = myGroup.substr(0, 10); - const auto nextPipeNum = pipeNum + 1; + const auto nextPipeNum = pipeNum.value() + 1; const auto samePipeSpawners = Game::zoneManager->GetSpawnersByName(myGroup); @@ -37,7 +33,7 @@ void FvBrickPuzzleServer::OnDie(Entity* self, Entity* killer) { samePipeSpawners[0]->Deactivate(); } - if (killer != nullptr && killer->IsPlayer()) { + if (killer && killer->IsPlayer()) { const auto nextPipe = pipeGroup + std::to_string(nextPipeNum); const auto nextPipeSpawners = Game::zoneManager->GetSpawnersByName(nextPipe); diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 6df5d0da..bb879dbd 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -208,8 +208,7 @@ int main(int argc, char** argv) { UserManager::Instance()->Initialize(); - bool dontGenerateDCF = false; - GeneralUtils::TryParse(Game::config->GetValue("dont_generate_dcf"), dontGenerateDCF); + const bool dontGenerateDCF = GeneralUtils::TryParse(Game::config->GetValue("dont_generate_dcf")).value_or(false); Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", dontGenerateDCF); Game::server = new dServer(masterIP, ourPort, instanceID, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::World, Game::config, &Game::lastSignal, zoneID); diff --git a/dZoneManager/Level.cpp b/dZoneManager/Level.cpp index 2606b46f..9524d908 100644 --- a/dZoneManager/Level.cpp +++ b/dZoneManager/Level.cpp @@ -14,6 +14,7 @@ #include "CDFeatureGatingTable.h" #include "CDClientManager.h" #include "AssetManager.h" +#include "ClientVersion.h" #include "dConfig.h" Level::Level(Zone* parentZone, const std::string& filepath) { @@ -211,12 +212,12 @@ void Level::ReadSceneObjectDataChunk(std::istream& file, Header& header) { CDFeatureGatingTable* featureGatingTable = CDClientManager::GetTable(); CDFeatureGating gating; - gating.major = 1; - gating.current = 10; - gating.minor = 64; - GeneralUtils::TryParse(Game::config->GetValue("version_major"), gating.major); - GeneralUtils::TryParse(Game::config->GetValue("version_current"), gating.current); - GeneralUtils::TryParse(Game::config->GetValue("version_minor"), gating.minor); + gating.major = + GeneralUtils::TryParse(Game::config->GetValue("version_major")).value_or(ClientVersion::major); + gating.current = + GeneralUtils::TryParse(Game::config->GetValue("version_current")).value_or(ClientVersion::current); + gating.minor = + GeneralUtils::TryParse(Game::config->GetValue("version_minor")).value_or(ClientVersion::minor); const auto zoneControlObject = Game::zoneManager->GetZoneControlObject(); DluAssert(zoneControlObject != nullptr); From 29666a1ff768ed01f581f783b12c2499cf82c839 Mon Sep 17 00:00:00 2001 From: jadebenn Date: Sat, 10 Feb 2024 13:44:40 -0600 Subject: [PATCH 16/50] chore: General cleanup roundup (#1444) * Moved unrelated changes out of the TryParse PR branch * const correctness and cstdint type usage * removing a few "== nullptr" * amf constexpr, const-correctness, and attrib tagging * update to account for feedback * Fixing accidentally included header and hopefully fixing the MacOS issue too * try reordering the amf3 specializations to fix the MacOS issue again * Amf3 template class member func instantiation fix * try including only on macos * Using if constexpr rather than specialization * Trying a different solution for the instantiation problem * Remove #include "dPlatforms.h" --- dChatServer/PlayerContainer.cpp | 9 - dChatServer/PlayerContainer.h | 7 +- dCommon/Amf3.h | 164 ++++++++++-------- dCommon/LDFFormat.h | 2 +- dCommon/dEnums/dCommonVars.h | 90 +++++----- dGame/dComponents/QuickBuildComponent.cpp | 66 ++++--- dGame/dComponents/QuickBuildComponent.h | 70 ++++---- .../AddStripMessage.cpp | 2 +- .../ControlBehaviorMessages/AddStripMessage.h | 2 +- .../BehaviorMessageBase.cpp | 14 +- .../BehaviorMessageBase.h | 12 +- .../02_server/Map/AM/AmDropshipComputer.cpp | 8 +- 12 files changed, 218 insertions(+), 228 deletions(-) diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index 7d8d7d97..dbbaeb9e 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -10,7 +10,6 @@ #include "Database.h" #include "eConnectionType.h" #include "eChatInternalMessageType.h" -#include "eGameMasterLevel.h" #include "ChatPackets.h" #include "dConfig.h" @@ -21,14 +20,6 @@ void PlayerContainer::Initialize() { GeneralUtils::TryParse(Game::config->GetValue("max_number_of_friends")).value_or(m_MaxNumberOfFriends); } -PlayerContainer::~PlayerContainer() { - m_Players.clear(); -} - -PlayerData::PlayerData() { - gmLevel = eGameMasterLevel::CIVILIAN; -} - TeamData::TeamData() { lootFlag = Game::config->GetValue("default_team_loot") == "0" ? 0 : 1; } diff --git a/dChatServer/PlayerContainer.h b/dChatServer/PlayerContainer.h index f34b1e54..3f2d783a 100644 --- a/dChatServer/PlayerContainer.h +++ b/dChatServer/PlayerContainer.h @@ -10,7 +10,7 @@ enum class eGameMasterLevel : uint8_t; struct IgnoreData { - IgnoreData(const std::string& name, const LWOOBJID& id) : playerName(name), playerId(id) {} + IgnoreData(const std::string& name, const LWOOBJID& id) : playerName{ name }, playerId{ id } {} inline bool operator==(const std::string& other) const noexcept { return playerName == other; } @@ -24,7 +24,6 @@ struct IgnoreData { }; struct PlayerData { - PlayerData(); operator bool() const noexcept { return playerID != LWOOBJID_EMPTY; } @@ -45,7 +44,7 @@ struct PlayerData { std::string playerName; std::vector friends; std::vector ignoredPlayers; - eGameMasterLevel gmLevel; + eGameMasterLevel gmLevel = static_cast(0); // CIVILLIAN bool isFTP = false; }; @@ -61,8 +60,6 @@ struct TeamData { class PlayerContainer { public: - ~PlayerContainer(); - void Initialize(); void InsertPlayer(Packet* packet); void RemovePlayer(Packet* packet); diff --git a/dCommon/Amf3.h b/dCommon/Amf3.h index 967313c7..dbafba1f 100644 --- a/dCommon/Amf3.h +++ b/dCommon/Amf3.h @@ -31,54 +31,68 @@ enum class eAmf : uint8_t { class AMFBaseValue { public: - virtual eAmf GetValueType() { return eAmf::Undefined; }; - AMFBaseValue() {}; - virtual ~AMFBaseValue() {}; + [[nodiscard]] constexpr virtual eAmf GetValueType() const noexcept { return eAmf::Undefined; } + constexpr AMFBaseValue() noexcept = default; + constexpr virtual ~AMFBaseValue() noexcept = default; }; -template +// AMFValue template class instantiations +template class AMFValue : public AMFBaseValue { public: - AMFValue() {}; - AMFValue(ValueType value) { SetValue(value); }; - virtual ~AMFValue() override {}; + AMFValue() = default; + AMFValue(const ValueType value) { m_Data = value; } + virtual ~AMFValue() override = default; - eAmf GetValueType() override { return eAmf::Undefined; }; + [[nodiscard]] constexpr eAmf GetValueType() const noexcept override; + + [[nodiscard]] const ValueType& GetValue() const { return m_Data; } + void SetValue(const ValueType value) { m_Data = value; } - const ValueType& GetValue() { return data; }; - void SetValue(ValueType value) { data = value; }; protected: - ValueType data; + ValueType m_Data; }; +// Explicit template class instantiations +template class AMFValue; +template class AMFValue; +template class AMFValue; +template class AMFValue; +template class AMFValue; +template class AMFValue; + +// AMFValue template class member function instantiations +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::Null; } +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return m_Data ? eAmf::True : eAmf::False; } +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::Integer; } +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::Integer; } +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::String; } +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::Double; } + +template +[[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::Undefined; } + // As a string this is much easier to write and read from a BitStream. -template<> +template <> class AMFValue : public AMFBaseValue { public: - AMFValue() {}; - AMFValue(const char* value) { SetValue(std::string(value)); }; - virtual ~AMFValue() override {}; + AMFValue() = default; + AMFValue(const char* value) { m_Data = value; } + virtual ~AMFValue() override = default; - eAmf GetValueType() override { return eAmf::String; }; + [[nodiscard]] constexpr eAmf GetValueType() const noexcept override { return eAmf::String; } - const std::string& GetValue() { return data; }; - void SetValue(std::string value) { data = value; }; + [[nodiscard]] const std::string& GetValue() const { return m_Data; } + void SetValue(const std::string& value) { m_Data = value; } protected: - std::string data; + std::string m_Data; }; -typedef AMFValue AMFNullValue; -typedef AMFValue AMFBoolValue; -typedef AMFValue AMFIntValue; -typedef AMFValue AMFStringValue; -typedef AMFValue AMFDoubleValue; - -template<> inline eAmf AMFValue::GetValueType() { return eAmf::Null; }; -template<> inline eAmf AMFValue::GetValueType() { return this->data ? eAmf::True : eAmf::False; }; -template<> inline eAmf AMFValue::GetValueType() { return eAmf::Integer; }; -template<> inline eAmf AMFValue::GetValueType() { return eAmf::Integer; }; -template<> inline eAmf AMFValue::GetValueType() { return eAmf::String; }; -template<> inline eAmf AMFValue::GetValueType() { return eAmf::Double; }; +using AMFNullValue = AMFValue; +using AMFBoolValue = AMFValue; +using AMFIntValue = AMFValue; +using AMFStringValue = AMFValue; +using AMFDoubleValue = AMFValue; /** * The AMFArrayValue object holds 2 types of lists: @@ -89,12 +103,11 @@ template<> inline eAmf AMFValue::GetValueType() { return eAmf::Double; } * and are not to be deleted by a caller. */ class AMFArrayValue : public AMFBaseValue { - - typedef std::unordered_map AMFAssociative; - typedef std::vector AMFDense; + using AMFAssociative = std::unordered_map; + using AMFDense = std::vector; public: - eAmf GetValueType() override { return eAmf::Array; }; + [[nodiscard]] constexpr eAmf GetValueType() const noexcept override { return eAmf::Array; } ~AMFArrayValue() override { for (auto valueToDelete : GetDense()) { @@ -109,17 +122,17 @@ public: valueToDelete.second = nullptr; } } - }; + } /** * Returns the Associative portion of the object */ - inline AMFAssociative& GetAssociative() { return this->associative; }; + [[nodiscard]] inline AMFAssociative& GetAssociative() noexcept { return this->associative; } /** * Returns the dense portion of the object */ - inline AMFDense& GetDense() { return this->dense; }; + [[nodiscard]] inline AMFDense& GetDense() noexcept { return this->dense; } /** * Inserts an AMFValue into the associative portion with the given key. @@ -135,8 +148,8 @@ public: * @return The inserted element if the type matched, * or nullptr if a key existed and was not the same type */ - template - std::pair*, bool> Insert(const std::string& key, ValueType value) { + template + [[maybe_unused]] std::pair*, bool> Insert(const std::string& key, const ValueType value) { auto element = associative.find(key); AMFValue* val = nullptr; bool found = true; @@ -148,10 +161,10 @@ public: found = false; } return std::make_pair(val, found); - }; + } // Associates an array with a string key - std::pair Insert(const std::string& key) { + [[maybe_unused]] std::pair Insert(const std::string& key) { auto element = associative.find(key); AMFArrayValue* val = nullptr; bool found = true; @@ -163,10 +176,10 @@ public: found = false; } return std::make_pair(val, found); - }; + } // Associates an array with an integer key - std::pair Insert(const uint32_t& index) { + [[maybe_unused]] std::pair Insert(const size_t index) { AMFArrayValue* val = nullptr; bool inserted = false; if (index >= dense.size()) { @@ -176,7 +189,7 @@ public: inserted = true; } return std::make_pair(dynamic_cast(dense.at(index)), inserted); - }; + } /** * @brief Inserts an AMFValue into the AMFArray key'd by index. @@ -188,8 +201,8 @@ public: * @return The inserted element, or nullptr if the type did not match * what was at the index. */ - template - std::pair*, bool> Insert(const uint32_t& index, ValueType value) { + template + [[maybe_unused]] std::pair*, bool> Insert(const size_t index, const ValueType value) { AMFValue* val = nullptr; bool inserted = false; if (index >= this->dense.size()) { @@ -199,7 +212,7 @@ public: inserted = true; } return std::make_pair(dynamic_cast*>(this->dense.at(index)), inserted); - }; + } /** * Inserts an AMFValue into the associative portion with the given key. @@ -210,7 +223,7 @@ public: * @param key The key to associate with the value * @param value The value to insert */ - void Insert(const std::string& key, AMFBaseValue* value) { + void Insert(const std::string& key, AMFBaseValue* const value) { auto element = associative.find(key); if (element != associative.end() && element->second) { delete element->second; @@ -218,7 +231,7 @@ public: } else { associative.insert(std::make_pair(key, value)); } - }; + } /** * Inserts an AMFValue into the associative portion with the given index. @@ -229,7 +242,7 @@ public: * @param key The key to associate with the value * @param value The value to insert */ - void Insert(const uint32_t index, AMFBaseValue* value) { + void Insert(const size_t index, AMFBaseValue* const value) { if (index < dense.size()) { AMFDense::iterator itr = dense.begin() + index; if (*itr) delete dense.at(index); @@ -237,7 +250,7 @@ public: dense.resize(index + 1); } dense.at(index) = value; - }; + } /** * Pushes an AMFValue into the back of the dense portion. @@ -249,10 +262,10 @@ public: * * @return The inserted pointer, or nullptr should the key already be in use. */ - template - inline AMFValue* Push(ValueType value) { + template + [[maybe_unused]] inline AMFValue* Push(const ValueType value) { return Insert(this->dense.size(), value).first; - }; + } /** * Removes the key from the associative portion @@ -261,7 +274,7 @@ public: * * @param key The key to remove from the associative portion */ - void Remove(const std::string& key, bool deleteValue = true) { + void Remove(const std::string& key, const bool deleteValue = true) { AMFAssociative::iterator it = this->associative.find(key); if (it != this->associative.end()) { if (deleteValue) delete it->second; @@ -272,7 +285,7 @@ public: /** * Pops the last element in the dense portion, deleting it in the process. */ - void Remove(const uint32_t index) { + void Remove(const size_t index) { if (!this->dense.empty() && index < this->dense.size()) { auto itr = this->dense.begin() + index; if (*itr) delete (*itr); @@ -284,29 +297,29 @@ public: if (!this->dense.empty()) Remove(this->dense.size() - 1); } - AMFArrayValue* GetArray(const std::string& key) { + [[nodiscard]] AMFArrayValue* GetArray(const std::string& key) { AMFAssociative::const_iterator it = this->associative.find(key); if (it != this->associative.end()) { return dynamic_cast(it->second); } return nullptr; - }; + } - AMFArrayValue* GetArray(const uint32_t index) { + [[nodiscard]] AMFArrayValue* GetArray(const size_t index) { return index >= this->dense.size() ? nullptr : dynamic_cast(this->dense.at(index)); - }; + } - inline AMFArrayValue* InsertArray(const std::string& key) { + [[maybe_unused]] inline AMFArrayValue* InsertArray(const std::string& key) { return static_cast(Insert(key).first); - }; + } - inline AMFArrayValue* InsertArray(const uint32_t index) { + [[maybe_unused]] inline AMFArrayValue* InsertArray(const size_t index) { return static_cast(Insert(index).first); - }; + } - inline AMFArrayValue* PushArray() { + [[maybe_unused]] inline AMFArrayValue* PushArray() { return static_cast(Insert(this->dense.size()).first); - }; + } /** * Gets an AMFValue by the key from the associative portion and converts it @@ -318,18 +331,18 @@ public: * @return The AMFValue */ template - AMFValue* Get(const std::string& key) const { + [[nodiscard]] AMFValue* Get(const std::string& key) const { AMFAssociative::const_iterator it = this->associative.find(key); return it != this->associative.end() ? dynamic_cast*>(it->second) : nullptr; - }; + } // Get from the array but dont cast it - AMFBaseValue* Get(const std::string& key) const { + [[nodiscard]] AMFBaseValue* Get(const std::string& key) const { AMFAssociative::const_iterator it = this->associative.find(key); return it != this->associative.end() ? it->second : nullptr; - }; + } /** * @brief Get an AMFValue object at a position in the dense portion. @@ -341,16 +354,17 @@ public: * @return The casted object, or nullptr. */ template - AMFValue* Get(uint32_t index) const { + [[nodiscard]] AMFValue* Get(const size_t index) const { return index < this->dense.size() ? dynamic_cast*>(this->dense.at(index)) : nullptr; - }; + } // Get from the dense but dont cast it - AMFBaseValue* Get(const uint32_t index) const { + [[nodiscard]] AMFBaseValue* Get(const size_t index) const { return index < this->dense.size() ? this->dense.at(index) : nullptr; - }; + } + private: /** * The associative portion. These values are key'd with strings to an AMFValue. diff --git a/dCommon/LDFFormat.h b/dCommon/LDFFormat.h index 7bcc91a2..3a4f2ea7 100644 --- a/dCommon/LDFFormat.h +++ b/dCommon/LDFFormat.h @@ -162,7 +162,7 @@ public: return new LDFData(key, value); } - inline static T Default = {}; + inline static const T Default = {}; }; // LDF Types diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index f4f8fdfb..d871e267 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -39,86 +39,84 @@ constexpr uint32_t lowFrameDelta = FRAMES_TO_MS(lowFramerate); //=========== TYPEDEFS ========== -typedef int32_t LOT; //!< A LOT -typedef int64_t LWOOBJID; //!< An object ID (should be unsigned actually but ok) -typedef int32_t TSkillID; //!< A skill ID -typedef uint32_t LWOCLONEID; //!< Used for Clone IDs -typedef uint16_t LWOMAPID; //!< Used for Map IDs -typedef uint16_t LWOINSTANCEID; //!< Used for Instance IDs -typedef uint32_t PROPERTYCLONELIST; //!< Used for Property Clone IDs -typedef uint32_t StripId; +using LOT = int32_t; //!< A LOT +using LWOOBJID = int64_t; //!< An object ID (should be unsigned actually but ok) +using TSkillID = int32_t; //!< A skill ID +using LWOCLONEID = uint32_t; //!< Used for Clone IDs +using LWOMAPID = uint16_t; //!< Used for Map IDs +using LWOINSTANCEID = uint16_t; //!< Used for Instance IDs +using PROPERTYCLONELIST = uint32_t; //!< Used for Property Clone IDs +using StripId = uint32_t; -const LWOOBJID LWOOBJID_EMPTY = 0; //!< An empty object ID -const LOT LOT_NULL = -1; //!< A null LOT -const int32_t LOOTTYPE_NONE = 0; //!< No loot type available -const float SECONDARY_PRIORITY = 1.0f; //!< Secondary Priority -const uint32_t INVENTORY_MAX = 9999999; //!< The Maximum Inventory Size -const uint32_t LWOCLONEID_INVALID = -1; //!< Invalid LWOCLONEID -const uint16_t LWOINSTANCEID_INVALID = -1; //!< Invalid LWOINSTANCEID -const uint16_t LWOMAPID_INVALID = -1; //!< Invalid LWOMAPID -const uint64_t LWOZONEID_INVALID = 0; //!< Invalid LWOZONEID +constexpr LWOOBJID LWOOBJID_EMPTY = 0; //!< An empty object ID +constexpr LOT LOT_NULL = -1; //!< A null LOT +constexpr int32_t LOOTTYPE_NONE = 0; //!< No loot type available +constexpr float SECONDARY_PRIORITY = 1.0f; //!< Secondary Priority +constexpr uint32_t INVENTORY_MAX = 9999999; //!< The Maximum Inventory Size +constexpr LWOCLONEID LWOCLONEID_INVALID = -1; //!< Invalid LWOCLONEID +constexpr LWOINSTANCEID LWOINSTANCEID_INVALID = -1; //!< Invalid LWOINSTANCEID +constexpr LWOMAPID LWOMAPID_INVALID = -1; //!< Invalid LWOMAPID +constexpr uint64_t LWOZONEID_INVALID = 0; //!< Invalid LWOZONEID -const float PI = 3.14159f; +constexpr float PI = 3.14159f; //============ STRUCTS ============== struct LWOSCENEID { public: - LWOSCENEID() { m_sceneID = -1; m_layerID = 0; } - LWOSCENEID(int sceneID) { m_sceneID = sceneID; m_layerID = 0; } - LWOSCENEID(int sceneID, unsigned int layerID) { m_sceneID = sceneID; m_layerID = layerID; } + constexpr LWOSCENEID() noexcept { m_sceneID = -1; m_layerID = 0; } + constexpr LWOSCENEID(int32_t sceneID) noexcept { m_sceneID = sceneID; m_layerID = 0; } + constexpr LWOSCENEID(int32_t sceneID, uint32_t layerID) noexcept { m_sceneID = sceneID; m_layerID = layerID; } - LWOSCENEID& operator=(const LWOSCENEID& rhs) { m_sceneID = rhs.m_sceneID; m_layerID = rhs.m_layerID; return *this; } - LWOSCENEID& operator=(const int rhs) { m_sceneID = rhs; m_layerID = 0; return *this; } + constexpr LWOSCENEID& operator=(const LWOSCENEID& rhs) noexcept { m_sceneID = rhs.m_sceneID; m_layerID = rhs.m_layerID; return *this; } + constexpr LWOSCENEID& operator=(const int32_t rhs) noexcept { m_sceneID = rhs; m_layerID = 0; return *this; } - bool operator<(const LWOSCENEID& rhs) const { return (m_sceneID < rhs.m_sceneID || (m_sceneID == rhs.m_sceneID && m_layerID < rhs.m_layerID)); } - bool operator<(const int rhs) const { return m_sceneID < rhs; } + constexpr bool operator<(const LWOSCENEID& rhs) const noexcept { return (m_sceneID < rhs.m_sceneID || (m_sceneID == rhs.m_sceneID && m_layerID < rhs.m_layerID)); } + constexpr bool operator<(const int32_t rhs) const noexcept { return m_sceneID < rhs; } - bool operator==(const LWOSCENEID& rhs) const { return (m_sceneID == rhs.m_sceneID && m_layerID == rhs.m_layerID); } - bool operator==(const int rhs) const { return m_sceneID == rhs; } + constexpr bool operator==(const LWOSCENEID& rhs) const noexcept { return (m_sceneID == rhs.m_sceneID && m_layerID == rhs.m_layerID); } + constexpr bool operator==(const int32_t rhs) const noexcept { return m_sceneID == rhs; } - const int GetSceneID() const { return m_sceneID; } - const unsigned int GetLayerID() const { return m_layerID; } + constexpr int32_t GetSceneID() const noexcept { return m_sceneID; } + constexpr uint32_t GetLayerID() const noexcept { return m_layerID; } - void SetSceneID(const int sceneID) { m_sceneID = sceneID; } - void SetLayerID(const unsigned int layerID) { m_layerID = layerID; } + constexpr void SetSceneID(const int32_t sceneID) noexcept { m_sceneID = sceneID; } + constexpr void SetLayerID(const uint32_t layerID) noexcept { m_layerID = layerID; } private: - int m_sceneID; - unsigned int m_layerID; + int32_t m_sceneID; + uint32_t m_layerID; }; struct LWOZONEID { public: - const LWOMAPID& GetMapID() const { return m_MapID; } - const LWOINSTANCEID& GetInstanceID() const { return m_InstanceID; } - const LWOCLONEID& GetCloneID() const { return m_CloneID; } + constexpr const LWOMAPID& GetMapID() const noexcept { return m_MapID; } + constexpr const LWOINSTANCEID& GetInstanceID() const noexcept { return m_InstanceID; } + constexpr const LWOCLONEID& GetCloneID() const noexcept { return m_CloneID; } //In order: def constr, constr, assign op - LWOZONEID() { m_MapID = LWOMAPID_INVALID; m_InstanceID = LWOINSTANCEID_INVALID; m_CloneID = LWOCLONEID_INVALID; } - LWOZONEID(const LWOMAPID& mapID, const LWOINSTANCEID& instanceID, const LWOCLONEID& cloneID) { m_MapID = mapID; m_InstanceID = instanceID; m_CloneID = cloneID; } - LWOZONEID(const LWOZONEID& replacement) { *this = replacement; } + constexpr LWOZONEID() noexcept = default; + constexpr LWOZONEID(const LWOMAPID& mapID, const LWOINSTANCEID& instanceID, const LWOCLONEID& cloneID) noexcept { m_MapID = mapID; m_InstanceID = instanceID; m_CloneID = cloneID; } + constexpr LWOZONEID(const LWOZONEID& replacement) noexcept { *this = replacement; } private: - LWOMAPID m_MapID; //1000 for VE, 1100 for AG, etc... - LWOINSTANCEID m_InstanceID; //Instances host the same world, but on a different dWorld process. - LWOCLONEID m_CloneID; //To differentiate between "your property" and "my property". Always 0 for non-prop worlds. + LWOMAPID m_MapID = LWOMAPID_INVALID; //1000 for VE, 1100 for AG, etc... + LWOINSTANCEID m_InstanceID = LWOINSTANCEID_INVALID; //Instances host the same world, but on a different dWorld process. + LWOCLONEID m_CloneID = LWOCLONEID_INVALID; //To differentiate between "your property" and "my property". Always 0 for non-prop worlds. }; -const LWOSCENEID LWOSCENEID_INVALID = -1; +constexpr LWOSCENEID LWOSCENEID_INVALID = -1; struct LWONameValue { uint32_t length = 0; //!< The length of the name std::u16string name; //!< The name - LWONameValue(void) {} + LWONameValue() = default; LWONameValue(const std::u16string& name) { this->name = name; this->length = static_cast(name.length()); } - - ~LWONameValue(void) {} }; struct FriendData { diff --git a/dGame/dComponents/QuickBuildComponent.cpp b/dGame/dComponents/QuickBuildComponent.cpp index 2514f194..6cef87d3 100644 --- a/dGame/dComponents/QuickBuildComponent.cpp +++ b/dGame/dComponents/QuickBuildComponent.cpp @@ -23,7 +23,7 @@ #include "CppScripts.h" -QuickBuildComponent::QuickBuildComponent(Entity* entity) : Component(entity) { +QuickBuildComponent::QuickBuildComponent(Entity* const entity) : Component{ entity } { std::u16string checkPreconditions = entity->GetVar(u"CheckPrecondition"); if (!checkPreconditions.empty()) { @@ -283,47 +283,47 @@ void QuickBuildComponent::DespawnActivator() { } } -Entity* QuickBuildComponent::GetActivator() { +Entity* QuickBuildComponent::GetActivator() const { return Game::entityManager->GetEntity(m_ActivatorId); } -NiPoint3 QuickBuildComponent::GetActivatorPosition() { +NiPoint3 QuickBuildComponent::GetActivatorPosition() const noexcept { return m_ActivatorPosition; } -float QuickBuildComponent::GetResetTime() { +float QuickBuildComponent::GetResetTime() const noexcept { return m_ResetTime; } -float QuickBuildComponent::GetCompleteTime() { +float QuickBuildComponent::GetCompleteTime() const noexcept { return m_CompleteTime; } -int QuickBuildComponent::GetTakeImagination() { +int32_t QuickBuildComponent::GetTakeImagination() const noexcept { return m_TakeImagination; } -bool QuickBuildComponent::GetInterruptible() { +bool QuickBuildComponent::GetInterruptible() const noexcept { return m_Interruptible; } -bool QuickBuildComponent::GetSelfActivator() { +bool QuickBuildComponent::GetSelfActivator() const noexcept { return m_SelfActivator; } -std::vector QuickBuildComponent::GetCustomModules() { +std::vector QuickBuildComponent::GetCustomModules() const noexcept { return m_CustomModules; } -int QuickBuildComponent::GetActivityId() { +int32_t QuickBuildComponent::GetActivityId() const noexcept { return m_ActivityId; } -int QuickBuildComponent::GetPostImaginationCost() { +int32_t QuickBuildComponent::GetPostImaginationCost() const noexcept { return m_PostImaginationCost; } -float QuickBuildComponent::GetTimeBeforeSmash() { +float QuickBuildComponent::GetTimeBeforeSmash() const noexcept { return m_TimeBeforeSmash; } @@ -332,24 +332,24 @@ eQuickBuildState QuickBuildComponent::GetState() const noexcept { } Entity* QuickBuildComponent::GetBuilder() const { - auto* builder = Game::entityManager->GetEntity(m_Builder); + auto* const builder = Game::entityManager->GetEntity(m_Builder); return builder; } -bool QuickBuildComponent::GetRepositionPlayer() const { +bool QuickBuildComponent::GetRepositionPlayer() const noexcept { return m_RepositionPlayer; } -void QuickBuildComponent::SetActivatorPosition(NiPoint3 value) { +void QuickBuildComponent::SetActivatorPosition(const NiPoint3& value) noexcept { m_ActivatorPosition = value; } -void QuickBuildComponent::SetResetTime(float value) { +void QuickBuildComponent::SetResetTime(const float value) noexcept { m_ResetTime = value; } -void QuickBuildComponent::SetCompleteTime(float value) { +void QuickBuildComponent::SetCompleteTime(const float value) noexcept { if (value < 0) { m_CompleteTime = 4.5f; } else { @@ -357,31 +357,31 @@ void QuickBuildComponent::SetCompleteTime(float value) { } } -void QuickBuildComponent::SetTakeImagination(int value) { +void QuickBuildComponent::SetTakeImagination(const int32_t value) noexcept { m_TakeImagination = value; } -void QuickBuildComponent::SetInterruptible(bool value) { +void QuickBuildComponent::SetInterruptible(const bool value) noexcept { m_Interruptible = value; } -void QuickBuildComponent::SetSelfActivator(bool value) { +void QuickBuildComponent::SetSelfActivator(const bool value) noexcept { m_SelfActivator = value; } -void QuickBuildComponent::SetCustomModules(std::vector value) { +void QuickBuildComponent::SetCustomModules(const std::vector& value) noexcept { m_CustomModules = value; } -void QuickBuildComponent::SetActivityId(int value) { +void QuickBuildComponent::SetActivityId(const int32_t value) noexcept { m_ActivityId = value; } -void QuickBuildComponent::SetPostImaginationCost(int value) { +void QuickBuildComponent::SetPostImaginationCost(const int32_t value) noexcept { m_PostImaginationCost = value; } -void QuickBuildComponent::SetTimeBeforeSmash(float value) { +void QuickBuildComponent::SetTimeBeforeSmash(const float value) noexcept { if (value < 0) { m_TimeBeforeSmash = 10.0f; } else { @@ -389,11 +389,11 @@ void QuickBuildComponent::SetTimeBeforeSmash(float value) { } } -void QuickBuildComponent::SetRepositionPlayer(bool value) { +void QuickBuildComponent::SetRepositionPlayer(const bool value) noexcept { m_RepositionPlayer = value; } -void QuickBuildComponent::StartQuickBuild(Entity* user) { +void QuickBuildComponent::StartQuickBuild(Entity* const user) { if (m_State == eQuickBuildState::OPEN || m_State == eQuickBuildState::COMPLETED || m_State == eQuickBuildState::INCOMPLETE) { m_Builder = user->GetObjectID(); @@ -426,10 +426,8 @@ void QuickBuildComponent::StartQuickBuild(Entity* user) { } } -void QuickBuildComponent::CompleteQuickBuild(Entity* user) { - if (user == nullptr) { - return; - } +void QuickBuildComponent::CompleteQuickBuild(Entity* const user) { + if (!user) return; auto* characterComponent = user->GetComponent(); if (characterComponent != nullptr) { @@ -518,7 +516,7 @@ void QuickBuildComponent::CompleteQuickBuild(Entity* user) { RenderComponent::PlayAnimation(user, u"rebuild-celebrate", 1.09f); } -void QuickBuildComponent::ResetQuickBuild(bool failed) { +void QuickBuildComponent::ResetQuickBuild(const bool failed) { Entity* builder = GetBuilder(); if (m_State == eQuickBuildState::BUILDING && builder) { @@ -553,7 +551,7 @@ void QuickBuildComponent::ResetQuickBuild(bool failed) { } } -void QuickBuildComponent::CancelQuickBuild(Entity* entity, eQuickBuildFailReason failReason, bool skipChecks) { +void QuickBuildComponent::CancelQuickBuild(Entity* const entity, const eQuickBuildFailReason failReason, const bool skipChecks) { if (m_State != eQuickBuildState::COMPLETED || skipChecks) { m_Builder = LWOOBJID_EMPTY; @@ -581,9 +579,7 @@ void QuickBuildComponent::CancelQuickBuild(Entity* entity, eQuickBuildFailReason Game::entityManager->SerializeEntity(m_Parent); } - if (entity == nullptr) { - return; - } + if (!entity) return; CharacterComponent* characterComponent = entity->GetComponent(); if (characterComponent) { diff --git a/dGame/dComponents/QuickBuildComponent.h b/dGame/dComponents/QuickBuildComponent.h index d9cc4190..556264a8 100644 --- a/dGame/dComponents/QuickBuildComponent.h +++ b/dGame/dComponents/QuickBuildComponent.h @@ -24,7 +24,7 @@ class QuickBuildComponent final : public Component { public: static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::QUICK_BUILD; - QuickBuildComponent(Entity* entity); + QuickBuildComponent(Entity* const entity); ~QuickBuildComponent() override; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; @@ -50,124 +50,124 @@ public: * Returns the entity that acts as the activator for this quickbuild * @return the entity that acts as the activator for this quickbuild */ - Entity* GetActivator(); + [[nodiscard]] Entity* GetActivator() const; /** * Returns the spawn position of the activator for this quickbuild, if any * @return the spawn position of the activator for this quickbuild, if any */ - NiPoint3 GetActivatorPosition(); + [[nodiscard]] NiPoint3 GetActivatorPosition() const noexcept; /** * Sets the spawn position for the activator of this quickbuild * @param value the spawn position to set for the activator */ - void SetActivatorPosition(NiPoint3 value); + void SetActivatorPosition(const NiPoint3& value) noexcept; /** * Returns the time it takes for the quickbuild to reset after being built * @return the time it takes for the quickbuild to reset after being built */ - float GetResetTime(); + [[nodiscard]] float GetResetTime() const noexcept; /** * Sets the time it takes for the quickbuild to reset after being built * @param value the reset time to set */ - void SetResetTime(float value); + void SetResetTime(const float value) noexcept; /** * Returns the time it takes to complete the quickbuild * @return the time it takes to complete the quickbuild */ - float GetCompleteTime(); + [[nodiscard]] float GetCompleteTime() const noexcept; /** * Sets the time it takes to complete the quickbuild * @param value the completion time to set */ - void SetCompleteTime(float value); + void SetCompleteTime(const float value) noexcept; /** * Returns the imagination that's taken when completing the quickbuild * @return the imagination that's taken when completing the quickbuild */ - int GetTakeImagination(); + [[nodiscard]] int32_t GetTakeImagination() const noexcept; /** * Sets the imagination that's taken when completing the quickbuild * @param value the imagination deduction to set */ - void SetTakeImagination(int value); + void SetTakeImagination(const int32_t value) noexcept; /** * Returns if the quickbuild can be interrupted, currently unused * @return if the quickbuild can be interrupted */ - bool GetInterruptible(); + [[nodiscard]] bool GetInterruptible() const noexcept; /** * Sets whether or not the quickbuild can be interrupted, currently unused * @param value true if the quickbuild may be interrupted, false otherwise */ - void SetInterruptible(bool value); + void SetInterruptible(const bool value) noexcept; /** * Returns whether or not this entity contains a built-in activator * @return whether or not this entity contains a built-in activator */ - bool GetSelfActivator(); + [[nodiscard]] bool GetSelfActivator() const noexcept; /** * Sets whether or not this entity contains a built-in activator. If set to false this will spawn activators on * each new quickbuild. * @param value whether or not this entity contains a built-in activator */ - void SetSelfActivator(bool value); + void SetSelfActivator(const bool value) noexcept; /** * Currently unused */ - std::vector GetCustomModules(); + [[nodiscard]] std::vector GetCustomModules() const noexcept; /** * Currently unused */ - void SetCustomModules(std::vector value); + void SetCustomModules(const std::vector& value) noexcept; /** * Returns the activity ID for participating in this quickbuild * @return the activity ID for participating in this quickbuild */ - int GetActivityId(); + [[nodiscard]] int32_t GetActivityId() const noexcept; /** * Sets the activity ID for participating in this quickbuild * @param value the activity ID to set */ - void SetActivityId(int value); + void SetActivityId(const int32_t value) noexcept; /** * Currently unused */ - int GetPostImaginationCost(); + [[nodiscard]] int32_t GetPostImaginationCost() const noexcept; /** * Currently unused */ - void SetPostImaginationCost(int value); + void SetPostImaginationCost(const int32_t value) noexcept; /** * Returns the time it takes for an incomplete quickbuild to be smashed automatically * @return the time it takes for an incomplete quickbuild to be smashed automatically */ - float GetTimeBeforeSmash(); + [[nodiscard]] float GetTimeBeforeSmash() const noexcept; /** * Sets the time it takes for an incomplete quickbuild to be smashed automatically * @param value the time to set */ - void SetTimeBeforeSmash(float value); + void SetTimeBeforeSmash(const float value) noexcept; /** * Returns the current quickbuild state @@ -179,19 +179,19 @@ public: * Returns the player that is currently building this quickbuild * @return the player that is currently building this quickbuild */ - Entity* GetBuilder() const; + [[nodiscard]] Entity* GetBuilder() const; /** * Returns whether or not the player is repositioned when initiating the quickbuild * @return whether or not the player is repositioned when initiating the quickbuild */ - bool GetRepositionPlayer() const; + [[nodiscard]] bool GetRepositionPlayer() const noexcept; /** * Sets whether or not the player is repositioned when initiating the quickbuild * @param value whether or not the player is repositioned when initiating the quickbuild */ - void SetRepositionPlayer(bool value); + void SetRepositionPlayer(const bool value) noexcept; /** * Adds a callback that is called when the quickbuild is completed @@ -209,7 +209,7 @@ public: * Resets the quickbuild * @param failed whether or not the player failed to complete the quickbuild, triggers an extra animation */ - void ResetQuickBuild(bool failed); + void ResetQuickBuild(const bool failed); /** * Cancels the quickbuild if it wasn't completed @@ -217,7 +217,7 @@ public: * @param failReason the reason the quickbuild was cancelled * @param skipChecks whether or not to skip the check for the quickbuild not being completed */ - void CancelQuickBuild(Entity* builder, eQuickBuildFailReason failReason, bool skipChecks = false); + void CancelQuickBuild(Entity* const builder, const eQuickBuildFailReason failReason, const bool skipChecks = false); private: /** * Whether or not the quickbuild state has been changed since we last serialized it. @@ -287,7 +287,7 @@ private: /** * The imagination that's deducted when completing the quickbuild */ - int m_TakeImagination = 0; + int32_t m_TakeImagination = 0; /** * Currently unused @@ -302,17 +302,17 @@ private: /** * Currently unused */ - std::vector m_CustomModules{}; + std::vector m_CustomModules{}; /** * The activity ID that players partake in when doing this quickbuild */ - int m_ActivityId = 0; + int32_t m_ActivityId = 0; /** * Currently unused */ - int m_PostImaginationCost = 0; + int32_t m_PostImaginationCost = 0; /** * The time it takes for the quickbuild to reset when it's not completed yet @@ -327,7 +327,7 @@ private: /** * The amount of imagination that was drained when building this quickbuild */ - int m_DrainedImagination = 0; + int32_t m_DrainedImagination = 0; /** * Whether to reposition the player or not when building @@ -337,7 +337,7 @@ private: /** * Currently unused */ - float m_SoftTimer = 0; + int32_t m_SoftTimer = 0; /** * The ID of the entity that's currently building the quickbuild @@ -353,13 +353,13 @@ private: * Starts the quickbuild for a certain entity * @param user the entity to start the quickbuild */ - void StartQuickBuild(Entity* user); + void StartQuickBuild(Entity* const user); /** * Completes the quickbuild for an entity, dropping loot and despawning the activator * @param user the entity that completed the quickbuild */ - void CompleteQuickBuild(Entity* user); + void CompleteQuickBuild(Entity* const user); }; #endif // QUICKBUILDCOMPONENT_H diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp index 6f0741dd..ac6e8db7 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp @@ -2,7 +2,7 @@ #include "Action.h" -AddStripMessage::AddStripMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { +AddStripMessage::AddStripMessage(AMFArrayValue* const arguments) : BehaviorMessageBase{ arguments } { actionContext = ActionContext(arguments); position = StripUiPosition(arguments); diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h index 5cceb510..2e2bf9a0 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h @@ -18,7 +18,7 @@ class AMFArrayValue; */ class AddStripMessage : public BehaviorMessageBase { public: - AddStripMessage(AMFArrayValue* arguments); + AddStripMessage(AMFArrayValue* const arguments); StripUiPosition GetPosition() const { return position; }; ActionContext GetActionContext() const { return actionContext; }; std::vector GetActionsToAdd() const; diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp index 0aad74dd..a49a8aeb 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp @@ -8,9 +8,9 @@ BehaviorMessageBase::BehaviorMessageBase(AMFArrayValue* arguments) { this->behaviorId = GetBehaviorIdFromArgument(arguments); } -int32_t BehaviorMessageBase::GetBehaviorIdFromArgument(AMFArrayValue* arguments) { - const auto* key = "BehaviorID"; - auto* behaviorIDValue = arguments->Get(key); +int32_t BehaviorMessageBase::GetBehaviorIdFromArgument(AMFArrayValue* const arguments) { + const char* const key = "BehaviorID"; + const auto* const behaviorIDValue = arguments->Get(key); if (behaviorIDValue && behaviorIDValue->GetValueType() == eAmf::String) { this->behaviorId = @@ -22,11 +22,9 @@ int32_t BehaviorMessageBase::GetBehaviorIdFromArgument(AMFArrayValue* arguments) return this->behaviorId; } -int32_t BehaviorMessageBase::GetActionIndexFromArgument(AMFArrayValue* arguments, const std::string& keyName) { - auto* actionIndexAmf = arguments->Get(keyName); - if (!actionIndexAmf) { - throw std::invalid_argument("Unable to find actionIndex"); - } +int32_t BehaviorMessageBase::GetActionIndexFromArgument(AMFArrayValue* const arguments, const std::string& keyName) const { + const auto* const actionIndexAmf = arguments->Get(keyName); + if (!actionIndexAmf) throw std::invalid_argument("Unable to find actionIndex"); return static_cast(actionIndexAmf->GetValue()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h index 8a841d7f..f55fde8e 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h @@ -15,13 +15,13 @@ enum class BehaviorState : uint32_t; */ class BehaviorMessageBase { public: - static inline int32_t DefaultBehaviorId = -1; - const int32_t GetBehaviorId() const { return behaviorId; }; - bool IsDefaultBehaviorId() { return behaviorId == DefaultBehaviorId; }; - BehaviorMessageBase(AMFArrayValue* arguments); + static constexpr int32_t DefaultBehaviorId = -1; + [[nodiscard]] int32_t GetBehaviorId() const { return behaviorId; }; + [[nodiscard]] bool IsDefaultBehaviorId() { return behaviorId == DefaultBehaviorId; }; + BehaviorMessageBase(AMFArrayValue* const arguments); protected: - int32_t GetBehaviorIdFromArgument(AMFArrayValue* arguments); - int32_t GetActionIndexFromArgument(AMFArrayValue* arguments, const std::string& keyName = "actionIndex"); + [[nodiscard]] int32_t GetBehaviorIdFromArgument(AMFArrayValue* const arguments); + [[nodiscard]] int32_t GetActionIndexFromArgument(AMFArrayValue* const arguments, const std::string& keyName = "actionIndex") const; int32_t behaviorId = DefaultBehaviorId; }; diff --git a/dScripts/02_server/Map/AM/AmDropshipComputer.cpp b/dScripts/02_server/Map/AM/AmDropshipComputer.cpp index 357187ef..e88ec468 100644 --- a/dScripts/02_server/Map/AM/AmDropshipComputer.cpp +++ b/dScripts/02_server/Map/AM/AmDropshipComputer.cpp @@ -12,16 +12,12 @@ void AmDropshipComputer::OnStartup(Entity* self) { void AmDropshipComputer::OnUse(Entity* self, Entity* user) { auto* quickBuildComponent = self->GetComponent(); - if (quickBuildComponent == nullptr || quickBuildComponent->GetState() != eQuickBuildState::COMPLETED) { - return; - } + if (!quickBuildComponent || quickBuildComponent->GetState() != eQuickBuildState::COMPLETED) return; auto* missionComponent = user->GetComponent(); auto* inventoryComponent = user->GetComponent(); - if (missionComponent == nullptr || inventoryComponent == nullptr) { - return; - } + if (!missionComponent || !inventoryComponent) return; if (inventoryComponent->GetLotCount(m_NexusTalonDataCard) != 0 || missionComponent->GetMission(979)->GetMissionState() == eMissionState::COMPLETE) { return; From ecaaea3175553e4392a69747f17dab123ee722cf Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Sun, 11 Feb 2024 00:08:22 -0600 Subject: [PATCH 17/50] chore: make predefined name unique when the name files are not provided (#1453) Multiple characters would not be allowed to be made since they would both have tha name INVALID, that is no longer the case --- dGame/UserManager.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index b98569eb..0fde2eb6 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -301,6 +301,7 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) const auto name = LUWStringName.GetAsString(); std::string predefinedName = GetPredefinedName(firstNameIndex, middleNameIndex, lastNameIndex); + LOT shirtLOT = FindCharShirtID(shirtColor, shirtStyle); LOT pantsLOT = FindCharPantsID(pantsColor); @@ -323,7 +324,7 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) } //Now that the name is ok, we can get an objectID from Master: - ObjectIDManager::RequestPersistentID([=, this](uint32_t objectID) { + ObjectIDManager::RequestPersistentID([=, this](uint32_t objectID) mutable { if (Database::Get()->GetCharacterInfo(objectID)) { LOG("Character object id unavailable, check object_id_tracker!"); WorldPackets::SendCharacterCreationResponse(sysAddr, eCharacterCreationResponse::OBJECT_ID_UNAVAILABLE); @@ -366,6 +367,14 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) bool nameOk = IsNamePreapproved(name); if (!nameOk && u->GetMaxGMLevel() > eGameMasterLevel::FORUM_MODERATOR) nameOk = true; + // If predefined name is invalid, change it to be their object id + // that way more than one player can create characters if the predefined name files are not provided + if (predefinedName == "INVALID") { + std::stringstream nameObjID; + nameObjID << "minifig" << objectID; + predefinedName = nameObjID.str(); + } + std::string_view nameToAssign = !name.empty() && nameOk ? name : predefinedName; std::string pendingName = !name.empty() && !nameOk ? name : ""; From f7e4a3262153185d47c4ddab1fa4bf0e8c660c59 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 10 Feb 2024 22:29:05 -0800 Subject: [PATCH 18/50] Fix no effect playing when picking up item (#1455) --- dGame/Entity.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 16169887..269b4cc4 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -1682,9 +1682,9 @@ void Entity::PickupItem(const LWOOBJID& objectID) { std::vector skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == p.second.lot); }); for (CDObjectSkills skill : skills) { CDSkillBehaviorTable* skillBehTable = CDClientManager::GetTable(); - CDSkillBehavior behaviorData = skillBehTable->GetSkillByID(skill.skillID); - SkillComponent::HandleUnmanaged(behaviorData.behaviorID, GetObjectID()); + auto* skillComponent = GetComponent(); + if (skillComponent) skillComponent->CastSkill(skill.skillID, GetObjectID(), GetObjectID()); auto* missionComponent = GetComponent(); From ddaac276fed48672462cadf04f563b85d79a34e9 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 10 Feb 2024 22:38:21 -0800 Subject: [PATCH 19/50] fix: Remove hard coded groups for spawners (#1454) * fix macros not trimming newline * Remove hardcoded spawner groups Was just missing an inline script implementation and using the wrong name --- dGame/dUtilities/SlashCommandHandler.cpp | 3 +++ .../Enemy/AG/BossSpiderQueenEnemyServer.cpp | 2 +- dScripts/02_server/Map/AG/NpcCowboyServer.cpp | 14 ++++++++++++++ dScripts/02_server/Map/AG/NpcWispServer.cpp | 12 +++++++----- dZoneManager/Spawner.cpp | 10 ---------- 5 files changed, 25 insertions(+), 16 deletions(-) diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 169426ab..cd938bab 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -631,6 +631,9 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (infile.good()) { std::string line; while (std::getline(infile, line)) { + // Do this in two separate calls to catch both \n and \r\n + line.erase(std::remove(line.begin(), line.end(), '\n'), line.end()); + line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); SlashCommandHandler::HandleChatCommand(GeneralUtils::ASCIIToUTF16(line), entity, sysAddr); } } else { diff --git a/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp b/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp index a8edb14a..40b248f5 100644 --- a/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp +++ b/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp @@ -179,7 +179,7 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { std::vector spiderEggs{}; - auto spooders = Game::entityManager->GetEntitiesInGroup("EGG"); + auto spooders = Game::entityManager->GetEntitiesInGroup("SpiderEggs"); for (auto spodder : spooders) { spiderEggs.push_back(spodder->GetObjectID()); } diff --git a/dScripts/02_server/Map/AG/NpcCowboyServer.cpp b/dScripts/02_server/Map/AG/NpcCowboyServer.cpp index 6dd212a4..996a99c2 100644 --- a/dScripts/02_server/Map/AG/NpcCowboyServer.cpp +++ b/dScripts/02_server/Map/AG/NpcCowboyServer.cpp @@ -1,6 +1,7 @@ #include "NpcCowboyServer.h" #include "eMissionState.h" #include "InventoryComponent.h" +#include "dZoneManager.h" void NpcCowboyServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { if (missionID != 1880) { @@ -23,4 +24,17 @@ void NpcCowboyServer::OnMissionDialogueOK(Entity* self, Entity* target, int miss } else if (missionState == eMissionState::READY_TO_COMPLETE || missionState == eMissionState::COMPLETE_READY_TO_COMPLETE) { inventoryComponent->RemoveItem(14378, 1); } + + // Next up hide or show the samples based on the mission state + int32_t visible = 1; + if (missionState == eMissionState::READY_TO_COMPLETE || missionState == eMissionState::COMPLETE_READY_TO_COMPLETE) { + visible = 0; + } + + auto spawners = Game::zoneManager->GetSpawnersByName("PlungerGunTargets"); + for (auto* spawner : spawners) { + for (const auto entity : spawner->GetSpawnedObjectIDs()) + GameMessages::SendNotifyClientObject(entity, u"SetVisibility", visible, 0, + target->GetObjectID(), "", target->GetSystemAddress()); + } } diff --git a/dScripts/02_server/Map/AG/NpcWispServer.cpp b/dScripts/02_server/Map/AG/NpcWispServer.cpp index e3b5398d..e087df24 100644 --- a/dScripts/02_server/Map/AG/NpcWispServer.cpp +++ b/dScripts/02_server/Map/AG/NpcWispServer.cpp @@ -1,9 +1,10 @@ #include "NpcWispServer.h" #include "InventoryComponent.h" -#include "EntityManager.h" +#include "dZoneManager.h" #include "Entity.h" #include "GameMessages.h" #include "eMissionState.h" +#include "Spawner.h" void NpcWispServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { if (missionID != 1849 && missionID != 1883) @@ -25,7 +26,7 @@ void NpcWispServer::OnMissionDialogueOK(Entity* self, Entity* target, int missio } // Next up hide or show the samples based on the mission state - auto visible = 1; + int32_t visible = 1; if (missionState == eMissionState::READY_TO_COMPLETE || missionState == eMissionState::COMPLETE_READY_TO_COMPLETE) { visible = 0; } @@ -35,9 +36,10 @@ void NpcWispServer::OnMissionDialogueOK(Entity* self, Entity* target, int missio : std::vector{ "MaelstromSamples", "MaelstromSamples2ndary1", "MaelstromSamples2ndary2" }; for (const auto& group : groups) { - auto samples = Game::entityManager->GetEntitiesInGroup(group); - for (auto* sample : samples) { - GameMessages::SendNotifyClientObject(sample->GetObjectID(), u"SetVisibility", visible, 0, + auto spawners = Game::zoneManager->GetSpawnersByName(group); + for (const auto* spawner : spawners) { + for (const auto objId : spawner->GetSpawnedObjectIDs()) + GameMessages::SendNotifyClientObject(objId, u"SetVisibility", visible, 0, target->GetObjectID(), "", target->GetSystemAddress()); } } diff --git a/dZoneManager/Spawner.cpp b/dZoneManager/Spawner.cpp index 31188907..3baf193f 100644 --- a/dZoneManager/Spawner.cpp +++ b/dZoneManager/Spawner.cpp @@ -25,16 +25,6 @@ Spawner::Spawner(const SpawnerInfo info) { m_Start = m_Info.noTimedSpawn; - //ssssh... - if (m_EntityInfo.lot == 14718) { //AG - MAELSTROM SAMPLE - m_Info.groups.emplace_back("MaelstromSamples"); - } - - if (m_EntityInfo.lot == 14375) //AG - SPIDER BOSS EGG - { - m_Info.groups.emplace_back("EGG"); - } - int timerCount = m_Info.amountMaintained; if (m_Info.amountMaintained > m_Info.nodes.size()) { From dfb2fd93b403a7f06899b457a5edf7980fcbabad Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 11 Feb 2024 12:28:25 -0800 Subject: [PATCH 20/50] chore: use ranges in EntityManager and touch up (#1451) * EntityManager: ranges and cleanup Use LWOOBJID for ghosting entities use ranges::views::values for associative container iteration remove dead code comment magic numbers little bit of optimization (not enough to be game changing or take the time to measure, they are free speedups anyways, we take those) use cstdint types * use size_t * use lwoobjid for ghost candidate --- dGame/EntityManager.cpp | 143 +++++++++++---------------- dGame/EntityManager.h | 4 +- dGame/dComponents/GhostComponent.cpp | 8 +- dGame/dComponents/GhostComponent.h | 8 +- 4 files changed, 66 insertions(+), 97 deletions(-) diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index e1f2f46e..fc9fa0f0 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -24,6 +24,7 @@ #include "eReplicaPacketType.h" #include "PlayerManager.h" #include "GhostComponent.h" +#include // Configure which zones have ghosting disabled, mostly small worlds. std::vector EntityManager::m_GhostingExcludedZones = { @@ -165,8 +166,8 @@ void EntityManager::DestroyEntity(Entity* entity) { } void EntityManager::SerializeEntities() { - for (int32_t i = 0; i < m_EntitiesToSerialize.size(); i++) { - const LWOOBJID toSerialize = m_EntitiesToSerialize.at(i); + for (size_t i = 0; i < m_EntitiesToSerialize.size(); i++) { + const LWOOBJID toSerialize = m_EntitiesToSerialize[i]; auto* entity = GetEntity(toSerialize); if (!entity) continue; @@ -195,8 +196,8 @@ void EntityManager::SerializeEntities() { } void EntityManager::KillEntities() { - for (int32_t i = 0; i < m_EntitiesToKill.size(); i++) { - const LWOOBJID toKill = m_EntitiesToKill.at(i); + for (size_t i = 0; i < m_EntitiesToKill.size(); i++) { + const LWOOBJID toKill = m_EntitiesToKill[i]; auto* entity = GetEntity(toKill); if (!entity) { @@ -214,8 +215,8 @@ void EntityManager::KillEntities() { } void EntityManager::DeleteEntities() { - for (int32_t i = 0; i < m_EntitiesToDelete.size(); i++) { - const LWOOBJID toDelete = m_EntitiesToDelete.at(i); + for (size_t i = 0; i < m_EntitiesToDelete.size(); i++) { + const LWOOBJID toDelete = m_EntitiesToDelete[i]; auto entityToDelete = GetEntity(toDelete); if (entityToDelete) { // Get all this info first before we delete the player. @@ -238,8 +239,8 @@ void EntityManager::DeleteEntities() { } void EntityManager::UpdateEntities(const float deltaTime) { - for (const auto& e : m_Entities) { - e.second->Update(deltaTime); + for (auto* entity : m_Entities | std::views::values) { + entity->Update(deltaTime); } SerializeEntities(); @@ -259,10 +260,10 @@ Entity* EntityManager::GetEntity(const LWOOBJID& objectId) const { std::vector EntityManager::GetEntitiesInGroup(const std::string& group) { std::vector entitiesInGroup; - for (const auto& entity : m_Entities) { - for (const auto& entityGroup : entity.second->GetGroups()) { + for (auto* entity : m_Entities | std::views::values) { + for (const auto& entityGroup : entity->GetGroups()) { if (entityGroup == group) { - entitiesInGroup.push_back(entity.second); + entitiesInGroup.push_back(entity); } } } @@ -272,10 +273,12 @@ std::vector EntityManager::GetEntitiesInGroup(const std::string& group) std::vector EntityManager::GetEntitiesByComponent(const eReplicaComponentType componentType) const { std::vector withComp; - for (const auto& entity : m_Entities) { - if (componentType != eReplicaComponentType::INVALID && !entity.second->HasComponent(componentType)) continue; + if (componentType != eReplicaComponentType::INVALID) { + for (auto* entity : m_Entities | std::views::values) { + if (!entity->HasComponent(componentType)) continue; - withComp.push_back(entity.second); + withComp.push_back(entity); + } } return withComp; } @@ -283,19 +286,19 @@ std::vector EntityManager::GetEntitiesByComponent(const eReplicaCompone std::vector EntityManager::GetEntitiesByLOT(const LOT& lot) const { std::vector entities; - for (const auto& entity : m_Entities) { - if (entity.second->GetLOT() == lot) - entities.push_back(entity.second); + for (auto* entity : m_Entities | std::views::values) { + if (entity->GetLOT() == lot) entities.push_back(entity); } return entities; } -std::vector EntityManager::GetEntitiesByProximity(NiPoint3 reference, float radius) const{ - std::vector entities = {}; - if (radius > 1000.0f) return entities; - for (const auto& entity : m_Entities) { - if (NiPoint3::Distance(reference, entity.second->GetPosition()) <= radius) entities.push_back(entity.second); +std::vector EntityManager::GetEntitiesByProximity(NiPoint3 reference, float radius) const { + std::vector entities; + if (radius <= 1000.0f) { // The client has a 1000 unit limit on this same logic, so we'll use the same limit + for (auto* entity : m_Entities | std::views::values) { + if (NiPoint3::Distance(reference, entity->GetPosition()) <= radius) entities.push_back(entity); + } } return entities; } @@ -309,12 +312,8 @@ Entity* EntityManager::GetSpawnPointEntity(const std::string& spawnName) const { // Lookup the spawn point entity in the map const auto& spawnPoint = m_SpawnPoints.find(spawnName); - if (spawnPoint == m_SpawnPoints.end()) { - return nullptr; - } - // Check if the spawn point entity is valid just in case - return GetEntity(spawnPoint->second); + return spawnPoint == m_SpawnPoints.end() ? nullptr : GetEntity(spawnPoint->second); } const std::unordered_map& EntityManager::GetSpawnPointEntities() const { @@ -340,29 +339,25 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr entity->SetNetworkId(networkId); } - const auto checkGhosting = entity->GetIsGhostingCandidate(); - - if (checkGhosting) { - const auto& iter = std::find(m_EntitiesToGhost.begin(), m_EntitiesToGhost.end(), entity); - - if (iter == m_EntitiesToGhost.end()) { + if (entity->GetIsGhostingCandidate()) { + if (std::find(m_EntitiesToGhost.begin(), m_EntitiesToGhost.end(), entity) == m_EntitiesToGhost.end()) { m_EntitiesToGhost.push_back(entity); } - } - if (checkGhosting && sysAddr == UNASSIGNED_SYSTEM_ADDRESS) { - CheckGhosting(entity); + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) { + CheckGhosting(entity); - return; + return; + } } m_SerializationCounter++; RakNet::BitStream stream; - stream.Write(ID_REPLICA_MANAGER_CONSTRUCTION); + stream.Write(ID_REPLICA_MANAGER_CONSTRUCTION); stream.Write(true); - stream.Write(entity->GetNetworkId()); + stream.Write(entity->GetNetworkId()); entity->WriteBaseReplicaData(&stream, eReplicaPacketType::CONSTRUCTION); entity->WriteComponents(&stream, eReplicaPacketType::CONSTRUCTION); @@ -395,9 +390,9 @@ void EntityManager::ConstructAllEntities(const SystemAddress& sysAddr) { //ZoneControl is special: ConstructEntity(m_ZoneControlEntity, sysAddr); - for (const auto& e : m_Entities) { - if (e.second && (e.second->GetSpawnerID() != 0 || e.second->GetLOT() == 1) && !e.second->GetIsGhostingCandidate()) { - ConstructEntity(e.second, sysAddr); + for (auto* entity : m_Entities | std::views::values) { + if (entity && (entity->GetSpawnerID() != 0 || entity->GetLOT() == 1) && !entity->GetIsGhostingCandidate()) { + ConstructEntity(entity, sysAddr); } } @@ -409,8 +404,8 @@ void EntityManager::DestructEntity(Entity* entity, const SystemAddress& sysAddr) RakNet::BitStream stream; - stream.Write(ID_REPLICA_MANAGER_DESTRUCTION); - stream.Write(entity->GetNetworkId()); + stream.Write(ID_REPLICA_MANAGER_DESTRUCTION); + stream.Write(entity->GetNetworkId()); Game::server->Send(&stream, sysAddr, sysAddr == UNASSIGNED_SYSTEM_ADDRESS); @@ -431,8 +426,8 @@ void EntityManager::SerializeEntity(Entity* entity) { } void EntityManager::DestructAllEntities(const SystemAddress& sysAddr) { - for (const auto& e : m_Entities) { - DestructEntity(e.second, sysAddr); + for (auto* entity : m_Entities | std::views::values) { + DestructEntity(entity, sysAddr); } } @@ -440,22 +435,12 @@ void EntityManager::SetGhostDistanceMax(float value) { m_GhostDistanceMaxSquared = value * value; } -float EntityManager::GetGhostDistanceMax() const { - return std::sqrt(m_GhostDistanceMaxSquared); -} - void EntityManager::SetGhostDistanceMin(float value) { m_GhostDistanceMinSqaured = value * value; } -float EntityManager::GetGhostDistanceMin() const { - return std::sqrt(m_GhostDistanceMinSqaured); -} - void EntityManager::QueueGhostUpdate(LWOOBJID playerID) { - const auto& iter = std::find(m_PlayersToUpdateGhosting.begin(), m_PlayersToUpdateGhosting.end(), playerID); - - if (iter == m_PlayersToUpdateGhosting.end()) { + if (std::find(m_PlayersToUpdateGhosting.begin(), m_PlayersToUpdateGhosting.end(), playerID) == m_PlayersToUpdateGhosting.end()) { m_PlayersToUpdateGhosting.push_back(playerID); } } @@ -475,26 +460,20 @@ void EntityManager::UpdateGhosting() { } void EntityManager::UpdateGhosting(Entity* player) { - if (player == nullptr) { - return; - } + if (!player) return; auto* missionComponent = player->GetComponent(); auto* ghostComponent = player->GetComponent(); - if (missionComponent == nullptr || !ghostComponent) { - return; - } + if (!missionComponent || !ghostComponent) return; const auto& referencePoint = ghostComponent->GetGhostReferencePoint(); const auto isOverride = ghostComponent->GetGhostOverride(); for (auto* entity : m_EntitiesToGhost) { - const auto isAudioEmitter = entity->GetLOT() == 6368; - const auto& entityPoint = entity->GetPosition(); - const int32_t id = entity->GetObjectID(); + const auto id = entity->GetObjectID(); const auto observed = ghostComponent->IsObserved(id); @@ -503,6 +482,7 @@ void EntityManager::UpdateGhosting(Entity* player) { auto ghostingDistanceMax = m_GhostDistanceMaxSquared; auto ghostingDistanceMin = m_GhostDistanceMinSqaured; + const auto isAudioEmitter = entity->GetLOT() == 6368; // https://explorer.lu/objects/6368 if (isAudioEmitter) { ghostingDistanceMax = ghostingDistanceMin; } @@ -541,30 +521,25 @@ void EntityManager::CheckGhosting(Entity* entity) { const auto& referencePoint = entity->GetPosition(); - auto ghostingDistanceMax = m_GhostDistanceMaxSquared; - auto ghostingDistanceMin = m_GhostDistanceMinSqaured; - - const auto isAudioEmitter = entity->GetLOT() == 6368; - for (auto* player : PlayerManager::GetAllPlayers()) { auto* ghostComponent = player->GetComponent(); if (!ghostComponent) continue; const auto& entityPoint = ghostComponent->GetGhostReferencePoint(); - const int32_t id = entity->GetObjectID(); + const auto id = entity->GetObjectID(); const auto observed = ghostComponent->IsObserved(id); const auto distance = NiPoint3::DistanceSquared(referencePoint, entityPoint); - if (observed && distance > ghostingDistanceMax) { + if (observed && distance > m_GhostDistanceMaxSquared) { ghostComponent->GhostEntity(id); DestructEntity(entity, player->GetSystemAddress()); entity->SetObservers(entity->GetObservers() - 1); - } else if (!observed && ghostingDistanceMin > distance) { + } else if (!observed && m_GhostDistanceMinSqaured > distance) { ghostComponent->ObserveEntity(id); ConstructEntity(entity, player->GetSystemAddress()); @@ -574,7 +549,7 @@ void EntityManager::CheckGhosting(Entity* entity) { } } -Entity* EntityManager::GetGhostCandidate(int32_t id) { +Entity* EntityManager::GetGhostCandidate(LWOOBJID id) const { for (auto* entity : m_EntitiesToGhost) { if (entity->GetObjectID() == id) { return entity; @@ -600,26 +575,22 @@ void EntityManager::ScheduleForKill(Entity* entity) { const auto objectId = entity->GetObjectID(); - if (std::count(m_EntitiesToKill.begin(), m_EntitiesToKill.end(), objectId)) { - return; + if (std::find(m_EntitiesToKill.begin(), m_EntitiesToKill.end(), objectId) != m_EntitiesToKill.end()) { + m_EntitiesToKill.push_back(objectId); } - - m_EntitiesToKill.push_back(objectId); } void EntityManager::ScheduleForDeletion(LWOOBJID entity) { - if (std::count(m_EntitiesToDelete.begin(), m_EntitiesToDelete.end(), entity)) { - return; + if (std::find(m_EntitiesToDelete.begin(), m_EntitiesToDelete.end(), entity) != m_EntitiesToDelete.end()) { + m_EntitiesToDelete.push_back(entity); } - - m_EntitiesToDelete.push_back(entity); } void EntityManager::FireEventServerSide(Entity* origin, std::string args) { - for (std::pair e : m_Entities) { - if (e.second) { - e.second->OnFireEventServerSide(origin, args); + for (const auto entity : m_Entities | std::views::values) { + if (entity) { + entity->OnFireEventServerSide(origin, args); } } } diff --git a/dGame/EntityManager.h b/dGame/EntityManager.h index 352b927b..abffe546 100644 --- a/dGame/EntityManager.h +++ b/dGame/EntityManager.h @@ -50,14 +50,12 @@ public: void DestructAllEntities(const SystemAddress& sysAddr); void SetGhostDistanceMax(float value); - float GetGhostDistanceMax() const; void SetGhostDistanceMin(float value); - float GetGhostDistanceMin() const; void QueueGhostUpdate(LWOOBJID playerID); void UpdateGhosting(); void UpdateGhosting(Entity* player); void CheckGhosting(Entity* entity); - Entity* GetGhostCandidate(int32_t id); + Entity* GetGhostCandidate(LWOOBJID id) const; bool GetGhostingEnabled() const; void ScheduleForKill(Entity* entity); diff --git a/dGame/dComponents/GhostComponent.cpp b/dGame/dComponents/GhostComponent.cpp index db12ce4d..3aea329a 100644 --- a/dGame/dComponents/GhostComponent.cpp +++ b/dGame/dComponents/GhostComponent.cpp @@ -8,7 +8,7 @@ GhostComponent::GhostComponent(Entity* parent) : Component(parent) { GhostComponent::~GhostComponent() { for (auto& observedEntity : m_ObservedEntities) { - if (observedEntity == 0) continue; + if (observedEntity == LWOOBJID_EMPTY) continue; auto* entity = Game::entityManager->GetGhostCandidate(observedEntity); if (!entity) continue; @@ -44,14 +44,14 @@ void GhostComponent::ConstructLimboEntities() { m_LimboConstructions.clear(); } -void GhostComponent::ObserveEntity(int32_t id) { +void GhostComponent::ObserveEntity(LWOOBJID id) { m_ObservedEntities.insert(id); } -bool GhostComponent::IsObserved(int32_t id) { +bool GhostComponent::IsObserved(LWOOBJID id) { return m_ObservedEntities.contains(id); } -void GhostComponent::GhostEntity(int32_t id) { +void GhostComponent::GhostEntity(LWOOBJID id) { m_ObservedEntities.erase(id); } diff --git a/dGame/dComponents/GhostComponent.h b/dGame/dComponents/GhostComponent.h index bc4f158d..de0fb886 100644 --- a/dGame/dComponents/GhostComponent.h +++ b/dGame/dComponents/GhostComponent.h @@ -33,18 +33,18 @@ public: void ConstructLimboEntities(); - void ObserveEntity(const int32_t id); + void ObserveEntity(const LWOOBJID id); - bool IsObserved(const int32_t id); + bool IsObserved(const LWOOBJID id); - void GhostEntity(const int32_t id); + void GhostEntity(const LWOOBJID id); private: NiPoint3 m_GhostReferencePoint; NiPoint3 m_GhostOverridePoint; - std::unordered_set m_ObservedEntities; + std::unordered_set m_ObservedEntities; std::unordered_set m_LimboConstructions; From c3fbc87f9e3f4e93f3967fb787d6c5a4174f19e5 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 11 Feb 2024 12:36:15 -0800 Subject: [PATCH 21/50] remove copy pasted logic (#1446) tested that the ninjago platforms and fire still works, tested that point of interest work as well Update PhantomPhysicsComponent.cpp --- dGame/dComponents/PhantomPhysicsComponent.cpp | 61 +++---------------- 1 file changed, 10 insertions(+), 51 deletions(-) diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index b3021415..592c2a6b 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -156,83 +156,42 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : PhysicsCompon //temp test if (info->physicsAsset == "miscellaneous\\misc_phys_10x1x5.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 10.0f, 5.0f, 1.0f); - - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position); - - dpWorld::AddEntity(m_dpEntity); } else if (info->physicsAsset == "miscellaneous\\misc_phys_640x640.hkx") { - // Move this down by 13.521004 units so it is still effectively at the same height as before - m_Position = m_Position - NiPoint3Constant::UNIT_Y * 13.521004f; // TODO Fix physics simulation to do simulation at high velocities due to bullet through paper problem... m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 1638.4f, 13.521004f * 2.0f, 1638.4f); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position); - - dpWorld::AddEntity(m_dpEntity); + // Move this down by 13.521004 units so it is still effectively at the same height as before + m_Position = m_Position - NiPoint3Constant::UNIT_Y * 13.521004f; } else if (info->physicsAsset == "env\\trigger_wall_tall.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 10.0f, 25.0f, 1.0f); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position); - dpWorld::AddEntity(m_dpEntity); } else if (info->physicsAsset == "env\\env_gen_placeholderphysics.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 20.0f, 20.0f, 20.0f); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position); - dpWorld::AddEntity(m_dpEntity); } else if (info->physicsAsset == "env\\POI_trigger_wall.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 1.0f, 12.5f, 20.0f); // Not sure what the real size is - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position); - dpWorld::AddEntity(m_dpEntity); } else if (info->physicsAsset == "env\\NG_NinjaGo\\env_ng_gen_gate_chamber_puzzle_ceiling_tile_falling_phantom.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 18.0f, 5.0f, 15.0f); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position + m_Rotation.GetForwardVector() * 7.5f); - dpWorld::AddEntity(m_dpEntity); + m_Position += m_Rotation.GetForwardVector() * 7.5f; } else if (info->physicsAsset == "env\\NG_NinjaGo\\ng_flamejet_brick_phantom.HKX") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 1.0f, 1.0f, 12.0f); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position + m_Rotation.GetForwardVector() * 6.0f); - dpWorld::AddEntity(m_dpEntity); + m_Position += m_Rotation.GetForwardVector() * 6.0f; } else if (info->physicsAsset == "env\\Ring_Trigger.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 6.0f, 6.0f, 6.0f); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position); - dpWorld::AddEntity(m_dpEntity); } else if (info->physicsAsset == "env\\vfx_propertyImaginationBall.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 4.5f); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position); - dpWorld::AddEntity(m_dpEntity); } else if (info->physicsAsset == "env\\env_won_fv_gas-blocking-volume.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 390.496826f, 111.467964f, 600.821534f, true); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); m_Position.y -= (111.467964f * m_Scale) / 2; - m_dpEntity->SetPosition(m_Position); - dpWorld::AddEntity(m_dpEntity); } else { - //LOG("This one is supposed to have %s", info->physicsAsset.c_str()); + // LOG_DEBUG("This one is supposed to have %s", info->physicsAsset.c_str()); //add fallback cube: m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 2.0f, 2.0f, 2.0f); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position); - dpWorld::AddEntity(m_dpEntity); } - + + m_dpEntity->SetScale(m_Scale); + m_dpEntity->SetRotation(m_Rotation); + m_dpEntity->SetPosition(m_Position); + dpWorld::AddEntity(m_dpEntity); } } From c7b3d9e817fbc30e4de191932d428b4dddaedd2d Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 11 Feb 2024 19:00:39 -0800 Subject: [PATCH 22/50] close trade window (#1457) --- dGame/TradingManager.cpp | 12 +++++++----- dGame/TradingManager.h | 4 ++-- dGame/dGameMessages/GameMessages.cpp | 4 ++-- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/dGame/TradingManager.cpp b/dGame/TradingManager.cpp index 3d9a209c..c7143354 100644 --- a/dGame/TradingManager.cpp +++ b/dGame/TradingManager.cpp @@ -104,7 +104,7 @@ void Trade::SetAccepted(LWOOBJID participant, bool value) { } Complete(); - TradingManager::Instance()->CancelTrade(m_TradeId); + TradingManager::Instance()->CancelTrade(LWOOBJID_EMPTY, m_TradeId, false); } } @@ -178,14 +178,14 @@ void Trade::Complete() { return; } -void Trade::Cancel() { +void Trade::Cancel(const LWOOBJID canceller) { auto* entityA = GetParticipantAEntity(); auto* entityB = GetParticipantBEntity(); if (entityA == nullptr || entityB == nullptr) return; - GameMessages::SendServerTradeCancel(entityA->GetObjectID(), entityA->GetSystemAddress()); - GameMessages::SendServerTradeCancel(entityB->GetObjectID(), entityB->GetSystemAddress()); + if (entityA->GetObjectID() != canceller || canceller == LWOOBJID_EMPTY) GameMessages::SendServerTradeCancel(entityA->GetObjectID(), entityA->GetSystemAddress()); + if (entityB->GetObjectID() != canceller || canceller == LWOOBJID_EMPTY) GameMessages::SendServerTradeCancel(entityB->GetObjectID(), entityB->GetSystemAddress()); } void Trade::SendUpdateToOther(LWOOBJID participant) { @@ -262,11 +262,13 @@ Trade* TradingManager::GetPlayerTrade(LWOOBJID playerId) const { return nullptr; } -void TradingManager::CancelTrade(LWOOBJID tradeId) { +void TradingManager::CancelTrade(const LWOOBJID canceller, LWOOBJID tradeId, const bool sendCancelMessage) { auto* trade = GetTrade(tradeId); if (trade == nullptr) return; + if (sendCancelMessage) trade->Cancel(canceller); + delete trade; trades.erase(tradeId); diff --git a/dGame/TradingManager.h b/dGame/TradingManager.h index ec0d332f..fa55aa9d 100644 --- a/dGame/TradingManager.h +++ b/dGame/TradingManager.h @@ -30,7 +30,7 @@ public: void SetAccepted(LWOOBJID participant, bool value); void Complete(); - void Cancel(); + void Cancel(const LWOOBJID canceller); void SendUpdateToOther(LWOOBJID participant); @@ -66,7 +66,7 @@ public: Trade* GetTrade(LWOOBJID tradeId) const; Trade* GetPlayerTrade(LWOOBJID playerId) const; - void CancelTrade(LWOOBJID tradeId); + void CancelTrade(const LWOOBJID canceller, LWOOBJID tradeId, const bool sendCancelMessage = true); Trade* NewTrade(LWOOBJID participantA, LWOOBJID participantB); private: diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 8b4d1f05..3c42f4db 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -3270,7 +3270,7 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* if (trade != nullptr) { if (!trade->IsParticipant(i64Invitee)) { - TradingManager::Instance()->CancelTrade(trade->GetTradeId()); + TradingManager::Instance()->CancelTrade(entity->GetObjectID(), trade->GetTradeId()); TradingManager::Instance()->NewTrade(entity->GetObjectID(), i64Invitee); } @@ -3295,7 +3295,7 @@ void GameMessages::HandleClientTradeCancel(RakNet::BitStream* inStream, Entity* LOG("Trade canceled from (%llu)", entity->GetObjectID()); - TradingManager::Instance()->CancelTrade(trade->GetTradeId()); + TradingManager::Instance()->CancelTrade(entity->GetObjectID(), trade->GetTradeId()); } void GameMessages::HandleClientTradeAccept(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { From b6af92ef81a8c9f93557ad0492f927d027343d22 Mon Sep 17 00:00:00 2001 From: jadebenn Date: Sun, 18 Feb 2024 00:38:26 -0600 Subject: [PATCH 23/50] refactor: Rewrite BehaviorMessage classes to use member initialization, preferred member naming conventions, and const-ref getters (#1456) * Split out BehaviorMessage class changes from PR #1452 * remove inclusion in ActionContext.h * add the arguments nullptr check back in * remove redundant std::string constructor calls * Update AddStripMessage.cpp - change push_back to emplace_back --- dCommon/Amf3.h | 8 ++-- dGame/dGameMessages/GameMessages.cpp | 2 +- dGame/dPropertyBehaviors/BlockDefinition.cpp | 8 ++-- dGame/dPropertyBehaviors/BlockDefinition.h | 21 +++++----- .../ControlBehaviorMessages/Action.cpp | 38 +++++++------------ .../ControlBehaviorMessages/Action.h | 21 +++++----- .../ControlBehaviorMessages/ActionContext.cpp | 21 ++++------ .../ControlBehaviorMessages/ActionContext.h | 17 +++++---- .../AddActionMessage.cpp | 13 ++++--- .../AddActionMessage.h | 18 +++++---- .../ControlBehaviorMessages/AddMessage.cpp | 10 ++--- .../ControlBehaviorMessages/AddMessage.h | 7 ++-- .../AddStripMessage.cpp | 23 +++++------ .../ControlBehaviorMessages/AddStripMessage.h | 18 +++++---- .../BehaviorMessageBase.cpp | 17 ++++----- .../BehaviorMessageBase.h | 15 ++++---- .../MergeStripsMessage.cpp | 12 +++--- .../MergeStripsMessage.h | 26 ++++++++----- .../MigrateActionsMessage.cpp | 14 +++---- .../MigrateActionsMessage.h | 31 +++++++++------ .../MoveToInventoryMessage.cpp | 8 ++-- .../MoveToInventoryMessage.h | 8 ++-- .../RearrangeStripMessage.cpp | 12 +++--- .../RearrangeStripMessage.h | 17 +++++---- .../RemoveActionsMessage.cpp | 9 +++-- .../RemoveActionsMessage.h | 13 ++++--- .../RemoveStripMessage.cpp | 7 ++-- .../RemoveStripMessage.h | 8 ++-- .../ControlBehaviorMessages/RenameMessage.cpp | 8 ++-- .../ControlBehaviorMessages/RenameMessage.h | 8 ++-- .../SplitStripMessage.cpp | 14 +++---- .../SplitStripMessage.h | 33 +++++++++------- .../StripUiPosition.cpp | 29 ++++++-------- .../ControlBehaviorMessages/StripUiPosition.h | 13 ++++--- .../UpdateActionMessage.cpp | 15 ++++---- .../UpdateActionMessage.h | 18 +++++---- .../UpdateStripUiMessage.cpp | 9 +++-- .../UpdateStripUiMessage.h | 13 ++++--- dGame/dPropertyBehaviors/ControlBehaviors.cpp | 22 +++++------ dGame/dPropertyBehaviors/ControlBehaviors.h | 15 ++++---- dGame/dPropertyBehaviors/PropertyBehavior.cpp | 13 ++----- dGame/dPropertyBehaviors/PropertyBehavior.h | 8 ++-- dGame/dPropertyBehaviors/State.cpp | 30 +++++++-------- dGame/dPropertyBehaviors/State.h | 3 +- dGame/dPropertyBehaviors/Strip.cpp | 25 ++++++------ dGame/dPropertyBehaviors/Strip.h | 5 ++- 46 files changed, 362 insertions(+), 341 deletions(-) diff --git a/dCommon/Amf3.h b/dCommon/Amf3.h index dbafba1f..c3077370 100644 --- a/dCommon/Amf3.h +++ b/dCommon/Amf3.h @@ -127,12 +127,12 @@ public: /** * Returns the Associative portion of the object */ - [[nodiscard]] inline AMFAssociative& GetAssociative() noexcept { return this->associative; } + [[nodiscard]] inline const AMFAssociative& GetAssociative() const noexcept { return this->associative; } /** * Returns the dense portion of the object */ - [[nodiscard]] inline AMFDense& GetDense() noexcept { return this->dense; } + [[nodiscard]] inline const AMFDense& GetDense() const noexcept { return this->dense; } /** * Inserts an AMFValue into the associative portion with the given key. @@ -297,7 +297,7 @@ public: if (!this->dense.empty()) Remove(this->dense.size() - 1); } - [[nodiscard]] AMFArrayValue* GetArray(const std::string& key) { + [[nodiscard]] AMFArrayValue* GetArray(const std::string& key) const { AMFAssociative::const_iterator it = this->associative.find(key); if (it != this->associative.end()) { return dynamic_cast(it->second); @@ -305,7 +305,7 @@ public: return nullptr; } - [[nodiscard]] AMFArrayValue* GetArray(const size_t index) { + [[nodiscard]] AMFArrayValue* GetArray(const size_t index) const { return index >= this->dense.size() ? nullptr : dynamic_cast(this->dense.at(index)); } diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 3c42f4db..c38ef880 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -2504,7 +2504,7 @@ void GameMessages::HandleControlBehaviors(RakNet::BitStream* inStream, Entity* e auto owner = PropertyManagementComponent::Instance()->GetOwner(); if (!owner) return; - ControlBehaviors::Instance().ProcessCommand(entity, sysAddr, static_cast(amfArguments.get()), command, owner); + ControlBehaviors::Instance().ProcessCommand(entity, static_cast(amfArguments.get()), command, owner); } void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { diff --git a/dGame/dPropertyBehaviors/BlockDefinition.cpp b/dGame/dPropertyBehaviors/BlockDefinition.cpp index 2950ac82..e67a90d8 100644 --- a/dGame/dPropertyBehaviors/BlockDefinition.cpp +++ b/dGame/dPropertyBehaviors/BlockDefinition.cpp @@ -2,8 +2,8 @@ BlockDefinition BlockDefinition::blockDefinitionDefault{}; -BlockDefinition::BlockDefinition(std::string defaultValue, float minimumValue, float maximumValue) { - this->defaultValue = defaultValue; - this->minimumValue = minimumValue; - this->maximumValue = maximumValue; +BlockDefinition::BlockDefinition(const std::string& defaultValue, const float minimumValue, const float maximumValue) + : m_DefaultValue{ defaultValue } + , m_MinimumValue{ minimumValue } + , m_MaximumValue{ maximumValue } { } diff --git a/dGame/dPropertyBehaviors/BlockDefinition.h b/dGame/dPropertyBehaviors/BlockDefinition.h index 3a5a6bf1..84722ea2 100644 --- a/dGame/dPropertyBehaviors/BlockDefinition.h +++ b/dGame/dPropertyBehaviors/BlockDefinition.h @@ -7,19 +7,20 @@ class AMFArrayValue; class BlockDefinition { public: - BlockDefinition(std::string defaultValue = "", float minimumValue = 0.0f, float maximumValue = 0.0f); + BlockDefinition(const std::string& defaultValue = "", const float minimumValue = 0.0f, const float maximumValue = 0.0f); static BlockDefinition blockDefinitionDefault; - std::string& GetDefaultValue() { return defaultValue; }; - float GetMinimumValue() { return minimumValue; }; - float GetMaximumValue() { return maximumValue; }; - void SetDefaultValue(std::string value) { defaultValue = value; }; - void SetMinimumValue(float value) { minimumValue = value; }; - void SetMaximumValue(float value) { maximumValue = value; }; + [[nodiscard]] const std::string& GetDefaultValue() const { return m_DefaultValue; } + [[nodiscard]] float GetMinimumValue() const noexcept { return m_MinimumValue; } + [[nodiscard]] float GetMaximumValue() const noexcept { return m_MaximumValue; } + void SetDefaultValue(const std::string& value) { m_DefaultValue = value; } + void SetMinimumValue(const float value) noexcept { m_MinimumValue = value; } + void SetMaximumValue(const float value) noexcept { m_MaximumValue = value; } + private: - std::string defaultValue; - float minimumValue; - float maximumValue; + std::string m_DefaultValue; + float m_MinimumValue; + float m_MaximumValue; }; #endif //!__BLOCKDEFINITION__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.cpp index 73f1391d..f9d3cec8 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.cpp @@ -1,46 +1,34 @@ #include "Action.h" #include "Amf3.h" -Action::Action() { - type = ""; - valueParameterName = ""; - valueParameterString = ""; - valueParameterDouble = 0.0; -} - -Action::Action(AMFArrayValue* arguments) { - type = ""; - valueParameterName = ""; - valueParameterString = ""; - valueParameterDouble = 0.0; - for (auto& [paramName, paramValue] : arguments->GetAssociative()) { +Action::Action(const AMFArrayValue* arguments) { + for (const auto& [paramName, paramValue] : arguments->GetAssociative()) { if (paramName == "Type") { if (paramValue->GetValueType() != eAmf::String) continue; - type = static_cast(paramValue)->GetValue(); + m_Type = static_cast(paramValue)->GetValue(); } else { - valueParameterName = paramName; + m_ValueParameterName = paramName; // Message is the only known string parameter - if (valueParameterName == "Message") { + if (m_ValueParameterName == "Message") { if (paramValue->GetValueType() != eAmf::String) continue; - valueParameterString = static_cast(paramValue)->GetValue(); + m_ValueParameterString = static_cast(paramValue)->GetValue(); } else { if (paramValue->GetValueType() != eAmf::Double) continue; - valueParameterDouble = static_cast(paramValue)->GetValue(); + m_ValueParameterDouble = static_cast(paramValue)->GetValue(); } } } } void Action::SendBehaviorBlocksToClient(AMFArrayValue& args) const { - auto* actionArgs = args.PushArray(); - actionArgs->Insert("Type", type); + auto* const actionArgs = args.PushArray(); + actionArgs->Insert("Type", m_Type); - auto valueParameterName = GetValueParameterName(); - if (valueParameterName.empty()) return; + if (m_ValueParameterName.empty()) return; - if (valueParameterName == "Message") { - actionArgs->Insert(valueParameterName, valueParameterString); + if (m_ValueParameterName == "Message") { + actionArgs->Insert(m_ValueParameterName, m_ValueParameterString); } else { - actionArgs->Insert(valueParameterName, valueParameterDouble); + actionArgs->Insert(m_ValueParameterName, m_ValueParameterDouble); } } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.h index df665889..c2bb7ed7 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.h @@ -11,19 +11,20 @@ class AMFArrayValue; */ class Action { public: - Action(); - Action(AMFArrayValue* arguments); - const std::string& GetType() const { return type; }; - const std::string& GetValueParameterName() const { return valueParameterName; }; - const std::string& GetValueParameterString() const { return valueParameterString; }; - const double GetValueParameterDouble() const { return valueParameterDouble; }; + Action() = default; + Action(const AMFArrayValue* arguments); + [[nodiscard]] const std::string& GetType() const { return m_Type; }; + [[nodiscard]] const std::string& GetValueParameterName() const { return m_ValueParameterName; }; + [[nodiscard]] const std::string& GetValueParameterString() const { return m_ValueParameterString; }; + [[nodiscard]] double GetValueParameterDouble() const noexcept { return m_ValueParameterDouble; }; void SendBehaviorBlocksToClient(AMFArrayValue& args) const; + private: - std::string type; - std::string valueParameterName; - std::string valueParameterString; - double valueParameterDouble; + double m_ValueParameterDouble{ 0.0 }; + std::string m_Type{ "" }; + std::string m_ValueParameterName{ "" }; + std::string m_ValueParameterString{ "" }; }; #endif //!__ACTION__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.cpp index c2ba2eeb..0cdfbddd 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.cpp @@ -4,27 +4,20 @@ #include "Amf3.h" -ActionContext::ActionContext() { - stripId = 0; - stateId = BehaviorState::HOME_STATE; +ActionContext::ActionContext(const AMFArrayValue* arguments, const std::string& customStateKey, const std::string& customStripKey) + : m_StripId{ GetStripIdFromArgument(arguments, customStripKey) } + , m_StateId{ GetBehaviorStateFromArgument(arguments, customStateKey) } { } -ActionContext::ActionContext(AMFArrayValue* arguments, std::string customStateKey, std::string customStripKey) { - stripId = 0; - stateId = BehaviorState::HOME_STATE; - stripId = GetStripIdFromArgument(arguments, customStripKey); - stateId = GetBehaviorStateFromArgument(arguments, customStateKey); -} - -BehaviorState ActionContext::GetBehaviorStateFromArgument(AMFArrayValue* arguments, const std::string& key) { - auto* stateIDValue = arguments->Get(key); +BehaviorState ActionContext::GetBehaviorStateFromArgument(const AMFArrayValue* arguments, const std::string& key) const { + const auto* const stateIDValue = arguments->Get(key); if (!stateIDValue) throw std::invalid_argument("Unable to find behavior state from argument \"" + key + "\""); return static_cast(stateIDValue->GetValue()); } -StripId ActionContext::GetStripIdFromArgument(AMFArrayValue* arguments, const std::string& key) { - auto* stripIdValue = arguments->Get(key); +StripId ActionContext::GetStripIdFromArgument(const AMFArrayValue* arguments, const std::string& key) const { + const auto* const stripIdValue = arguments->Get(key); if (!stripIdValue) throw std::invalid_argument("Unable to find strip ID from argument \"" + key + "\""); return static_cast(stripIdValue->GetValue()); diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.h index 91e91e72..7013e84e 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.h @@ -12,15 +12,16 @@ class AMFArrayValue; */ class ActionContext { public: - ActionContext(); - ActionContext(AMFArrayValue* arguments, std::string customStateKey = "stateID", std::string customStripKey = "stripID"); - const StripId GetStripId() const { return stripId; }; - const BehaviorState GetStateId() const { return stateId; }; + ActionContext() noexcept = default; + ActionContext(const AMFArrayValue* arguments, const std::string& customStateKey = "stateID", const std::string& customStripKey = "stripID"); + [[nodiscard]] StripId GetStripId() const noexcept { return m_StripId; }; + [[nodiscard]] BehaviorState GetStateId() const noexcept { return m_StateId; }; + private: - BehaviorState GetBehaviorStateFromArgument(AMFArrayValue* arguments, const std::string& key); - StripId GetStripIdFromArgument(AMFArrayValue* arguments, const std::string& key); - StripId stripId; - BehaviorState stateId; + [[nodiscard]] BehaviorState GetBehaviorStateFromArgument(const AMFArrayValue* arguments, const std::string& key) const; + [[nodiscard]] StripId GetStripIdFromArgument(const AMFArrayValue* arguments, const std::string& key) const; + StripId m_StripId{ 0 }; + BehaviorState m_StateId{ BehaviorState::HOME_STATE }; }; #endif //!__ACTIONCONTEXT__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp index 36d9a3dc..44b1e9ab 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp @@ -1,13 +1,14 @@ #include "AddActionMessage.h" -AddActionMessage::AddActionMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - actionContext = ActionContext(arguments); - actionIndex = GetActionIndexFromArgument(arguments); +AddActionMessage::AddActionMessage(const AMFArrayValue* arguments) + : BehaviorMessageBase{ arguments } + , m_ActionIndex{ GetActionIndexFromArgument(arguments) } + , m_ActionContext{ arguments } { - auto* actionValue = arguments->GetArray("action"); + const auto* const actionValue = arguments->GetArray("action"); if (!actionValue) return; - action = Action(actionValue); + m_Action = Action{ actionValue }; - LOG_DEBUG("actionIndex %i stripId %i stateId %i type %s valueParameterName %s valueParameterString %s valueParameterDouble %f behaviorId %i", actionIndex, actionContext.GetStripId(), actionContext.GetStateId(), action.GetType().c_str(), action.GetValueParameterName().c_str(), action.GetValueParameterString().c_str(), action.GetValueParameterDouble(), behaviorId); + LOG_DEBUG("actionIndex %i stripId %i stateId %i type %s valueParameterName %s valueParameterString %s valueParameterDouble %f m_BehaviorId %i", m_ActionIndex, m_ActionContext.GetStripId(), m_ActionContext.GetStateId(), m_Action.GetType().c_str(), m_Action.GetValueParameterName().c_str(), m_Action.GetValueParameterString().c_str(), m_Action.GetValueParameterDouble(), m_BehaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.h index ac3a9612..a8737dd7 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.h @@ -13,14 +13,18 @@ class AMFArrayValue; */ class AddActionMessage : public BehaviorMessageBase { public: - AddActionMessage(AMFArrayValue* arguments); - int32_t GetActionIndex() const { return actionIndex; }; - Action GetAction() const { return action; }; - ActionContext GetActionContext() const { return actionContext; }; + AddActionMessage(const AMFArrayValue* arguments); + + [[nodiscard]] int32_t GetActionIndex() const noexcept { return m_ActionIndex; }; + + [[nodiscard]] const Action& GetAction() const noexcept { return m_Action; }; + + [[nodiscard]] const ActionContext& GetActionContext() const noexcept { return m_ActionContext; }; + private: - int32_t actionIndex = -1; - ActionContext actionContext; - Action action; + int32_t m_ActionIndex{ -1 }; + ActionContext m_ActionContext; + Action m_Action; }; #endif //!__ADDACTIONMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.cpp index cf96ab13..9c103334 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.cpp @@ -1,11 +1,9 @@ #include "AddMessage.h" -AddMessage::AddMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - behaviorIndex = 0; - auto* behaviorIndexValue = arguments->Get("BehaviorIndex"); - +AddMessage::AddMessage(const AMFArrayValue* arguments) : BehaviorMessageBase{ arguments } { + const auto* const behaviorIndexValue = arguments->Get("BehaviorIndex"); if (!behaviorIndexValue) return; - behaviorIndex = static_cast(behaviorIndexValue->GetValue()); - LOG_DEBUG("behaviorId %i index %i", behaviorId, behaviorIndex); + m_BehaviorIndex = static_cast(behaviorIndexValue->GetValue()); + LOG_DEBUG("behaviorId %i index %i", m_BehaviorId, m_BehaviorIndex); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.h index 76627665..0832d687 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.h @@ -9,10 +9,11 @@ */ class AddMessage : public BehaviorMessageBase { public: - AddMessage(AMFArrayValue* arguments); - const uint32_t GetBehaviorIndex() const { return behaviorIndex; }; + AddMessage(const AMFArrayValue* arguments); + [[nodiscard]] uint32_t GetBehaviorIndex() const noexcept { return m_BehaviorIndex; }; + private: - uint32_t behaviorIndex; + uint32_t m_BehaviorIndex{ 0 }; }; #endif //!__ADDMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp index ac6e8db7..064ba2e9 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp @@ -2,27 +2,24 @@ #include "Action.h" -AddStripMessage::AddStripMessage(AMFArrayValue* const arguments) : BehaviorMessageBase{ arguments } { - actionContext = ActionContext(arguments); - position = StripUiPosition(arguments); +AddStripMessage::AddStripMessage(const AMFArrayValue* arguments) + : BehaviorMessageBase{ arguments } + , m_Position{ arguments } + , m_ActionContext{ arguments } { - auto* strip = arguments->GetArray("strip"); + const auto* const strip = arguments->GetArray("strip"); if (!strip) return; - auto* actions = strip->GetArray("actions"); + const auto* const actions = strip->GetArray("actions"); if (!actions) return; for (uint32_t actionNumber = 0; actionNumber < actions->GetDense().size(); actionNumber++) { - auto* actionValue = actions->GetArray(actionNumber); + const auto* const actionValue = actions->GetArray(actionNumber); if (!actionValue) continue; - actionsToAdd.push_back(Action(actionValue)); + m_ActionsToAdd.emplace_back(actionValue); - LOG_DEBUG("xPosition %f yPosition %f stripId %i stateId %i behaviorId %i t %s valueParameterName %s valueParameterString %s valueParameterDouble %f", position.GetX(), position.GetY(), actionContext.GetStripId(), actionContext.GetStateId(), behaviorId, actionsToAdd.back().GetType().c_str(), actionsToAdd.back().GetValueParameterName().c_str(), actionsToAdd.back().GetValueParameterString().c_str(), actionsToAdd.back().GetValueParameterDouble()); + LOG_DEBUG("xPosition %f yPosition %f stripId %i stateId %i behaviorId %i t %s valueParameterName %s valueParameterString %s valueParameterDouble %f", m_Position.GetX(), m_Position.GetY(), m_ActionContext.GetStripId(), m_ActionContext.GetStateId(), m_BehaviorId, m_ActionsToAdd.back().GetType().c_str(), m_ActionsToAdd.back().GetValueParameterName().c_str(), m_ActionsToAdd.back().GetValueParameterString().c_str(), m_ActionsToAdd.back().GetValueParameterDouble()); } - LOG_DEBUG("number of actions %i", actionsToAdd.size()); -} - -std::vector AddStripMessage::GetActionsToAdd() const { - return actionsToAdd; + LOG_DEBUG("number of actions %i", m_ActionsToAdd.size()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h index 2e2bf9a0..dbd70421 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h @@ -18,14 +18,18 @@ class AMFArrayValue; */ class AddStripMessage : public BehaviorMessageBase { public: - AddStripMessage(AMFArrayValue* const arguments); - StripUiPosition GetPosition() const { return position; }; - ActionContext GetActionContext() const { return actionContext; }; - std::vector GetActionsToAdd() const; + AddStripMessage(const AMFArrayValue* arguments); + + [[nodiscard]] const StripUiPosition& GetPosition() const noexcept { return m_Position; } + + [[nodiscard]] const ActionContext& GetActionContext() const noexcept { return m_ActionContext; } + + [[nodiscard]] const std::vector& GetActionsToAdd() const noexcept { return m_ActionsToAdd; } + private: - StripUiPosition position; - ActionContext actionContext; - std::vector actionsToAdd; + StripUiPosition m_Position; + ActionContext m_ActionContext; + std::vector m_ActionsToAdd; }; #endif //!__ADDSTRIPMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp index a49a8aeb..f7688e1a 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp @@ -4,25 +4,22 @@ #include "BehaviorStates.h" #include "dCommonVars.h" -BehaviorMessageBase::BehaviorMessageBase(AMFArrayValue* arguments) { - this->behaviorId = GetBehaviorIdFromArgument(arguments); -} - -int32_t BehaviorMessageBase::GetBehaviorIdFromArgument(AMFArrayValue* const arguments) { - const char* const key = "BehaviorID"; +int32_t BehaviorMessageBase::GetBehaviorIdFromArgument(const AMFArrayValue* arguments) { + static constexpr const char* key = "BehaviorID"; const auto* const behaviorIDValue = arguments->Get(key); + int32_t behaviorId = DefaultBehaviorId; if (behaviorIDValue && behaviorIDValue->GetValueType() == eAmf::String) { - this->behaviorId = - GeneralUtils::TryParse(behaviorIDValue->GetValue()).value_or(this->behaviorId); + behaviorId = + GeneralUtils::TryParse(behaviorIDValue->GetValue()).value_or(behaviorId); } else if (arguments->Get(key) && arguments->Get(key)->GetValueType() != eAmf::Undefined) { throw std::invalid_argument("Unable to find behavior ID"); } - return this->behaviorId; + return behaviorId; } -int32_t BehaviorMessageBase::GetActionIndexFromArgument(AMFArrayValue* const arguments, const std::string& keyName) const { +int32_t BehaviorMessageBase::GetActionIndexFromArgument(const AMFArrayValue* arguments, const std::string& keyName) const { const auto* const actionIndexAmf = arguments->Get(keyName); if (!actionIndexAmf) throw std::invalid_argument("Unable to find actionIndex"); diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h index f55fde8e..cadf33bf 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h @@ -15,14 +15,15 @@ enum class BehaviorState : uint32_t; */ class BehaviorMessageBase { public: - static constexpr int32_t DefaultBehaviorId = -1; - [[nodiscard]] int32_t GetBehaviorId() const { return behaviorId; }; - [[nodiscard]] bool IsDefaultBehaviorId() { return behaviorId == DefaultBehaviorId; }; - BehaviorMessageBase(AMFArrayValue* const arguments); + static constexpr int32_t DefaultBehaviorId{ -1 }; + BehaviorMessageBase(const AMFArrayValue* arguments) : m_BehaviorId{ GetBehaviorIdFromArgument(arguments) } {} + [[nodiscard]] int32_t GetBehaviorId() const noexcept { return m_BehaviorId; } + [[nodiscard]] bool IsDefaultBehaviorId() const noexcept { return m_BehaviorId == DefaultBehaviorId; } + protected: - [[nodiscard]] int32_t GetBehaviorIdFromArgument(AMFArrayValue* const arguments); - [[nodiscard]] int32_t GetActionIndexFromArgument(AMFArrayValue* const arguments, const std::string& keyName = "actionIndex") const; - int32_t behaviorId = DefaultBehaviorId; + [[nodiscard]] int32_t GetBehaviorIdFromArgument(const AMFArrayValue* arguments); + [[nodiscard]] int32_t GetActionIndexFromArgument(const AMFArrayValue* arguments, const std::string& keyName = "actionIndex") const; + int32_t m_BehaviorId{ DefaultBehaviorId }; }; #endif //!__BEHAVIORMESSAGEBASE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp index 18327ecf..d5a83714 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp @@ -1,11 +1,11 @@ #include "MergeStripsMessage.h" -MergeStripsMessage::MergeStripsMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - sourceActionContext = ActionContext(arguments, "srcStateID", "srcStripID"); +MergeStripsMessage::MergeStripsMessage(const AMFArrayValue* arguments) + : BehaviorMessageBase{ arguments } + , m_DstActionIndex{ GetActionIndexFromArgument(arguments, "dstActionIndex") } + , m_SourceActionContext{ arguments, "srcStateID", "srcStripID" } + , m_DestinationActionContext{ arguments, "dstStateID", "dstStripID" } { - destinationActionContext = ActionContext(arguments, "dstStateID", "dstStripID"); - dstActionIndex = GetActionIndexFromArgument(arguments, "dstActionIndex"); - - LOG_DEBUG("srcstripId %i dststripId %i srcstateId %i dststateId %i dstactionIndex %i behaviorId %i", sourceActionContext.GetStripId(), destinationActionContext.GetStripId(), sourceActionContext.GetStateId(), destinationActionContext.GetStateId(), dstActionIndex, behaviorId); + LOG_DEBUG("srcstripId %i dststripId %i srcstateId %i dststateId %i dstactionIndex %i behaviorId %i", m_SourceActionContext.GetStripId(), m_DestinationActionContext.GetStripId(), m_SourceActionContext.GetStateId(), m_DestinationActionContext.GetStateId(), m_DstActionIndex, m_BehaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.h index 7fa4d3a8..970a744d 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.h @@ -13,17 +13,23 @@ class AMFArrayValue; */ class MergeStripsMessage : public BehaviorMessageBase { public: - MergeStripsMessage(AMFArrayValue* arguments); - int32_t GetDstActionIndex() const { return dstActionIndex; }; - ActionContext GetSourceActionContext() const { return sourceActionContext; }; - ActionContext GetDestinationActionContext() const { return destinationActionContext; }; - const std::vector& GetMigratedActions() const { return migratedActions; }; - void SetMigratedActions(std::vector::const_iterator start, std::vector::const_iterator end) { migratedActions.assign(start, end); }; + MergeStripsMessage(const AMFArrayValue* arguments); + + [[nodiscard]] int32_t GetDstActionIndex() const noexcept { return m_DstActionIndex; } + + [[nodiscard]] const ActionContext& GetSourceActionContext() const noexcept { return m_SourceActionContext; } + + [[nodiscard]] const ActionContext& GetDestinationActionContext() const noexcept { return m_DestinationActionContext; } + + [[nodiscard]] const std::vector& GetMigratedActions() const noexcept { return m_MigratedActions; } + + void SetMigratedActions(std::vector::const_iterator start, std::vector::const_iterator end) { m_MigratedActions.assign(start, end); }; + private: - std::vector migratedActions; - ActionContext sourceActionContext; - ActionContext destinationActionContext; - int32_t dstActionIndex; + int32_t m_DstActionIndex; + std::vector m_MigratedActions; + ActionContext m_SourceActionContext; + ActionContext m_DestinationActionContext; }; #endif //!__MERGESTRIPSMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp index 4d45429b..8fa2cb5b 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp @@ -1,11 +1,11 @@ #include "MigrateActionsMessage.h" -MigrateActionsMessage::MigrateActionsMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - sourceActionContext = ActionContext(arguments, "srcStateID", "srcStripID"); - srcActionIndex = GetActionIndexFromArgument(arguments, "srcActionIndex"); +MigrateActionsMessage::MigrateActionsMessage(const AMFArrayValue* arguments) + : BehaviorMessageBase{ arguments } + , m_SrcActionIndex{ GetActionIndexFromArgument(arguments, "srcActionIndex") } + , m_DstActionIndex{ GetActionIndexFromArgument(arguments, "dstActionIndex") } + , m_SourceActionContext{ arguments, "srcStateID", "srcStripID" } + , m_DestinationActionContext{ arguments, "dstStateID", "dstStripID" } { - destinationActionContext = ActionContext(arguments, "dstStateID", "dstStripID"); - dstActionIndex = GetActionIndexFromArgument(arguments, "dstActionIndex"); - - LOG_DEBUG("srcactionIndex %i dstactionIndex %i srcstripId %i dststripId %i srcstateId %i dststateId %i behaviorId %i", srcActionIndex, dstActionIndex, sourceActionContext.GetStripId(), destinationActionContext.GetStripId(), sourceActionContext.GetStateId(), destinationActionContext.GetStateId(), behaviorId); + LOG_DEBUG("srcactionIndex %i dstactionIndex %i srcstripId %i dststripId %i srcstateId %i dststateId %i behaviorId %i", m_SrcActionIndex, m_DstActionIndex, m_SourceActionContext.GetStripId(), m_DestinationActionContext.GetStripId(), m_SourceActionContext.GetStateId(), m_DestinationActionContext.GetStateId(), m_BehaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.h index 2f1ac243..e3671185 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.h @@ -13,19 +13,26 @@ class AMFArrayValue; */ class MigrateActionsMessage : public BehaviorMessageBase { public: - MigrateActionsMessage(AMFArrayValue* arguments); - int32_t GetSrcActionIndex() const { return srcActionIndex; }; - int32_t GetDstActionIndex() const { return dstActionIndex; }; - ActionContext GetSourceActionContext() const { return sourceActionContext; }; - ActionContext GetDestinationActionContext() const { return destinationActionContext; }; - const std::vector& GetMigratedActions() const { return migratedActions; }; - void SetMigratedActions(std::vector::const_iterator start, std::vector::const_iterator end) { migratedActions.assign(start, end); }; + MigrateActionsMessage(const AMFArrayValue* arguments); + + [[nodiscard]] int32_t GetSrcActionIndex() const noexcept { return m_SrcActionIndex; } + + [[nodiscard]] int32_t GetDstActionIndex() const noexcept { return m_DstActionIndex; } + + [[nodiscard]] const ActionContext& GetSourceActionContext() const noexcept { return m_SourceActionContext; } + + [[nodiscard]] const ActionContext& GetDestinationActionContext() const noexcept { return m_DestinationActionContext; } + + [[nodiscard]] const std::vector& GetMigratedActions() const noexcept { return m_MigratedActions; } + + void SetMigratedActions(std::vector::const_iterator start, std::vector::const_iterator end) { m_MigratedActions.assign(start, end); } + private: - std::vector migratedActions; - ActionContext sourceActionContext; - ActionContext destinationActionContext; - int32_t srcActionIndex; - int32_t dstActionIndex; + int32_t m_SrcActionIndex; + int32_t m_DstActionIndex; + std::vector m_MigratedActions; + ActionContext m_SourceActionContext; + ActionContext m_DestinationActionContext; }; #endif //!__MIGRATEACTIONSMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.cpp index 5195e676..01709f70 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.cpp @@ -1,9 +1,9 @@ #include "MoveToInventoryMessage.h" -MoveToInventoryMessage::MoveToInventoryMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - auto* behaviorIndexValue = arguments->Get("BehaviorIndex"); +MoveToInventoryMessage::MoveToInventoryMessage(const AMFArrayValue* arguments) : BehaviorMessageBase{ arguments } { + const auto* const behaviorIndexValue = arguments->Get("BehaviorIndex"); if (!behaviorIndexValue) return; - behaviorIndex = static_cast(behaviorIndexValue->GetValue()); - LOG_DEBUG("behaviorId %i behaviorIndex %i", behaviorId, behaviorIndex); + m_BehaviorIndex = static_cast(behaviorIndexValue->GetValue()); + LOG_DEBUG("behaviorId %i behaviorIndex %i", m_BehaviorId, m_BehaviorIndex); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.h index dc105766..9a383469 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.h @@ -7,15 +7,15 @@ class AMFArrayValue; /** * @brief Sent when a player moves a Behavior A at position B to their inventory. - * */ #pragma warning("This Control Behavior Message does not have a test yet. Non-developers can ignore this warning.") class MoveToInventoryMessage : public BehaviorMessageBase { public: - MoveToInventoryMessage(AMFArrayValue* arguments); - const uint32_t GetBehaviorIndex() const { return behaviorIndex; }; + MoveToInventoryMessage(const AMFArrayValue* arguments); + [[nodiscard]] uint32_t GetBehaviorIndex() const noexcept { return m_BehaviorIndex; }; + private: - uint32_t behaviorIndex; + uint32_t m_BehaviorIndex; }; #endif //!__MOVETOINVENTORYMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp index d612ae2a..0c3689fa 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp @@ -1,10 +1,10 @@ #include "RearrangeStripMessage.h" -RearrangeStripMessage::RearrangeStripMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - actionContext = ActionContext(arguments); - srcActionIndex = GetActionIndexFromArgument(arguments, "srcActionIndex"); +RearrangeStripMessage::RearrangeStripMessage(const AMFArrayValue* arguments) + : BehaviorMessageBase{ arguments } + , m_SrcActionIndex{ GetActionIndexFromArgument(arguments, "srcActionIndex") } + , m_DstActionIndex{ GetActionIndexFromArgument(arguments, "dstActionIndex") } + , m_ActionContext{ arguments } { - dstActionIndex = GetActionIndexFromArgument(arguments, "dstActionIndex"); - - LOG_DEBUG("srcactionIndex %i dstactionIndex %i stripId %i behaviorId %i stateId %i", srcActionIndex, dstActionIndex, actionContext.GetStripId(), behaviorId, actionContext.GetStateId()); + LOG_DEBUG("srcactionIndex %i dstactionIndex %i stripId %i behaviorId %i stateId %i", m_SrcActionIndex, m_DstActionIndex, m_ActionContext.GetStripId(), m_BehaviorId, m_ActionContext.GetStateId()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.h index db12c046..054fbf3e 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.h @@ -10,14 +10,17 @@ */ class RearrangeStripMessage : public BehaviorMessageBase { public: - RearrangeStripMessage(AMFArrayValue* arguments); - int32_t GetSrcActionIndex() const { return srcActionIndex; }; - int32_t GetDstActionIndex() const { return dstActionIndex; }; - ActionContext GetActionContext() const { return actionContext; }; + RearrangeStripMessage(const AMFArrayValue* arguments); + + [[nodiscard]] int32_t GetSrcActionIndex() const noexcept { return m_SrcActionIndex; } + [[nodiscard]] int32_t GetDstActionIndex() const noexcept { return m_DstActionIndex; } + + [[nodiscard]] const ActionContext& GetActionContext() const noexcept { return m_ActionContext; } + private: - ActionContext actionContext; - int32_t srcActionIndex; - int32_t dstActionIndex; + int32_t m_SrcActionIndex; + int32_t m_DstActionIndex; + ActionContext m_ActionContext; }; #endif //!__REARRANGESTRIPMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp index c6164c6f..ab13cd20 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp @@ -1,8 +1,9 @@ #include "RemoveActionsMessage.h" -RemoveActionsMessage::RemoveActionsMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - actionContext = ActionContext(arguments); - actionIndex = GetActionIndexFromArgument(arguments); +RemoveActionsMessage::RemoveActionsMessage(const AMFArrayValue* arguments) + : BehaviorMessageBase{ arguments } + , m_ActionIndex{ GetActionIndexFromArgument(arguments) } + , m_ActionContext{ arguments } { - LOG_DEBUG("behaviorId %i actionIndex %i stripId %i stateId %i", behaviorId, actionIndex, actionContext.GetStripId(), actionContext.GetStateId()); + LOG_DEBUG("behaviorId %i actionIndex %i stripId %i stateId %i", m_BehaviorId, m_ActionIndex, m_ActionContext.GetStripId(), m_ActionContext.GetStateId()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.h index 860df0af..7e212206 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.h @@ -12,12 +12,15 @@ class AMFArrayValue; */ class RemoveActionsMessage : public BehaviorMessageBase { public: - RemoveActionsMessage(AMFArrayValue* arguments); - int32_t GetActionIndex() const { return actionIndex; }; - ActionContext GetActionContext() const { return actionContext; }; + RemoveActionsMessage(const AMFArrayValue* arguments); + + [[nodiscard]] int32_t GetActionIndex() const noexcept { return m_ActionIndex; } + + [[nodiscard]] const ActionContext& GetActionContext() const noexcept { return m_ActionContext; } + private: - ActionContext actionContext; - int32_t actionIndex; + int32_t m_ActionIndex; + ActionContext m_ActionContext; }; #endif //!__REMOVEACTIONSMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp index b70beece..371faf1c 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp @@ -1,7 +1,8 @@ #include "RemoveStripMessage.h" -RemoveStripMessage::RemoveStripMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - actionContext = ActionContext(arguments); +RemoveStripMessage::RemoveStripMessage(const AMFArrayValue* arguments) + : BehaviorMessageBase{ arguments } + , m_ActionContext{ arguments } { - LOG_DEBUG("stripId %i stateId %i behaviorId %i", actionContext.GetStripId(), actionContext.GetStateId(), behaviorId); + LOG_DEBUG("stripId %i stateId %i behaviorId %i", m_ActionContext.GetStripId(), m_ActionContext.GetStateId(), m_BehaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.h index 6a32ab0c..a65949e8 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.h @@ -10,10 +10,12 @@ */ class RemoveStripMessage : public BehaviorMessageBase { public: - RemoveStripMessage(AMFArrayValue* arguments); - ActionContext GetActionContext() const { return actionContext; }; + RemoveStripMessage(const AMFArrayValue* arguments); + + const ActionContext& GetActionContext() const noexcept { return m_ActionContext; } + private: - ActionContext actionContext; + ActionContext m_ActionContext; }; #endif //!__REMOVESTRIPMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.cpp index 17365be2..d9c73f6a 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.cpp @@ -1,9 +1,9 @@ #include "RenameMessage.h" -RenameMessage::RenameMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - auto* nameAmf = arguments->Get("Name"); +RenameMessage::RenameMessage(const AMFArrayValue* arguments) : BehaviorMessageBase{ arguments } { + const auto* const nameAmf = arguments->Get("Name"); if (!nameAmf) return; - name = nameAmf->GetValue(); - LOG_DEBUG("behaviorId %i n %s", behaviorId, name.c_str()); + m_Name = nameAmf->GetValue(); + LOG_DEBUG("behaviorId %i n %s", m_BehaviorId, m_Name.c_str()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.h index 3f4119d2..e7174296 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.h @@ -7,14 +7,14 @@ class AMFArrayValue; /** * @brief Sent when a player renames this behavior - * */ class RenameMessage : public BehaviorMessageBase { public: - RenameMessage(AMFArrayValue* arguments); - const std::string& GetName() const { return name; }; + RenameMessage(const AMFArrayValue* arguments); + [[nodiscard]] const std::string& GetName() const { return m_Name; }; + private: - std::string name; + std::string m_Name; }; #endif //!__RENAMEMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp index 45dad737..9c35d1ba 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp @@ -1,11 +1,11 @@ #include "SplitStripMessage.h" -SplitStripMessage::SplitStripMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - sourceActionContext = ActionContext(arguments, "srcStateID", "srcStripID"); - srcActionIndex = GetActionIndexFromArgument(arguments, "srcActionIndex"); +SplitStripMessage::SplitStripMessage(const AMFArrayValue* arguments) + : BehaviorMessageBase{ arguments } + , m_SrcActionIndex{ GetActionIndexFromArgument(arguments, "srcActionIndex") } + , m_SourceActionContext{ arguments, "srcStateID", "srcStripID" } + , m_DestinationActionContext{ arguments, "dstStateID", "dstStripID" } + , m_DestinationPosition{ arguments, "dstStripUI" } { - destinationActionContext = ActionContext(arguments, "dstStateID", "dstStripID"); - destinationPosition = StripUiPosition(arguments, "dstStripUI"); - - LOG_DEBUG("behaviorId %i xPosition %f yPosition %f sourceStrip %i destinationStrip %i sourceState %i destinationState %i srcActindex %i", behaviorId, destinationPosition.GetX(), destinationPosition.GetY(), sourceActionContext.GetStripId(), destinationActionContext.GetStripId(), sourceActionContext.GetStateId(), destinationActionContext.GetStateId(), srcActionIndex); + LOG_DEBUG("behaviorId %i xPosition %f yPosition %f sourceStrip %i destinationStrip %i sourceState %i destinationState %i srcActindex %i", m_BehaviorId, m_DestinationPosition.GetX(), m_DestinationPosition.GetY(), m_SourceActionContext.GetStripId(), m_DestinationActionContext.GetStripId(), m_SourceActionContext.GetStateId(), m_DestinationActionContext.GetStateId(), m_SrcActionIndex); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.h index e41d50eb..6cdcc5c3 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.h @@ -14,20 +14,27 @@ class AMFArrayValue; */ class SplitStripMessage : public BehaviorMessageBase { public: - SplitStripMessage(AMFArrayValue* arguments); - ActionContext GetSourceActionContext() const { return sourceActionContext; }; - ActionContext GetDestinationActionContext() const { return destinationActionContext; }; - int32_t GetSrcActionIndex() const { return srcActionIndex; }; - StripUiPosition GetPosition() const { return destinationPosition; }; - const std::vector& GetTransferredActions() const { return transferredActions; }; - void SetTransferredActions(std::vector::const_iterator begin, std::vector::const_iterator end) { transferredActions.assign(begin, end); }; -private: - ActionContext sourceActionContext; - ActionContext destinationActionContext; - int32_t srcActionIndex; - StripUiPosition destinationPosition; + SplitStripMessage(const AMFArrayValue* arguments); + + [[nodiscard]] int32_t GetSrcActionIndex() const noexcept { return m_SrcActionIndex; } - std::vector transferredActions; + [[nodiscard]] const ActionContext& GetSourceActionContext() const noexcept { return m_SourceActionContext; } + + [[nodiscard]] const ActionContext& GetDestinationActionContext() const noexcept { return m_DestinationActionContext; } + + [[nodiscard]] const StripUiPosition& GetPosition() const noexcept { return m_DestinationPosition; } + + [[nodiscard]] const std::vector& GetTransferredActions() const noexcept { return m_TransferredActions; } + + void SetTransferredActions(std::vector::const_iterator begin, std::vector::const_iterator end) { m_TransferredActions.assign(begin, end); }; + +private: + int32_t m_SrcActionIndex; + ActionContext m_SourceActionContext; + ActionContext m_DestinationActionContext; + StripUiPosition m_DestinationPosition; + + std::vector m_TransferredActions; }; #endif //!__SPLITSTRIPMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.cpp index 8b2d1d36..0acbfb3f 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.cpp @@ -2,27 +2,22 @@ #include "Amf3.h" -StripUiPosition::StripUiPosition() { - xPosition = 0.0; - yPosition = 0.0; -} - -StripUiPosition::StripUiPosition(AMFArrayValue* arguments, std::string uiKeyName) { - xPosition = 0.0; - yPosition = 0.0; - auto* uiArray = arguments->GetArray(uiKeyName); +StripUiPosition::StripUiPosition(const AMFArrayValue* arguments, const std::string& uiKeyName) { + const auto* const uiArray = arguments->GetArray(uiKeyName); if (!uiArray) return; - auto* xPositionValue = uiArray->Get("x"); - auto* yPositionValue = uiArray->Get("y"); - if (!xPositionValue || !yPositionValue) return; + const auto* const xPositionValue = uiArray->Get("x"); + if (!xPositionValue) return; - yPosition = yPositionValue->GetValue(); - xPosition = xPositionValue->GetValue(); + const auto* const yPositionValue = uiArray->Get("y"); + if (!yPositionValue) return; + + m_YPosition = yPositionValue->GetValue(); + m_XPosition = xPositionValue->GetValue(); } void StripUiPosition::SendBehaviorBlocksToClient(AMFArrayValue& args) const { - auto* uiArgs = args.InsertArray("ui"); - uiArgs->Insert("x", xPosition); - uiArgs->Insert("y", yPosition); + auto* const uiArgs = args.InsertArray("ui"); + uiArgs->Insert("x", m_XPosition); + uiArgs->Insert("y", m_YPosition); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.h index 92578cdc..6371b465 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.h @@ -9,14 +9,15 @@ class AMFArrayValue; */ class StripUiPosition { public: - StripUiPosition(); - StripUiPosition(AMFArrayValue* arguments, std::string uiKeyName = "ui"); + StripUiPosition() noexcept = default; + StripUiPosition(const AMFArrayValue* arguments, const std::string& uiKeyName = "ui"); void SendBehaviorBlocksToClient(AMFArrayValue& args) const; - double GetX() const { return xPosition; }; - double GetY() const { return yPosition; }; + [[nodiscard]] double GetX() const noexcept { return m_XPosition; } + [[nodiscard]] double GetY() const noexcept { return m_YPosition; } + private: - double xPosition; - double yPosition; + double m_XPosition{ 0.0 }; + double m_YPosition{ 0.0 }; }; #endif //!__STRIPUIPOSITION__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp index 924a9e62..68b97917 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp @@ -2,14 +2,15 @@ #include "Action.h" -UpdateActionMessage::UpdateActionMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - actionContext = ActionContext(arguments); +UpdateActionMessage::UpdateActionMessage(const AMFArrayValue* arguments) + : BehaviorMessageBase{ arguments } + , m_ActionIndex{ GetActionIndexFromArgument(arguments) } + , m_ActionContext{ arguments } { - auto* actionValue = arguments->GetArray("action"); + const auto* const actionValue = arguments->GetArray("action"); if (!actionValue) return; + + m_Action = Action{ actionValue }; - action = Action(actionValue); - actionIndex = GetActionIndexFromArgument(arguments); - - LOG_DEBUG("type %s valueParameterName %s valueParameterString %s valueParameterDouble %f behaviorId %i actionIndex %i stripId %i stateId %i", action.GetType().c_str(), action.GetValueParameterName().c_str(), action.GetValueParameterString().c_str(), action.GetValueParameterDouble(), behaviorId, actionIndex, actionContext.GetStripId(), actionContext.GetStateId()); + LOG_DEBUG("type %s valueParameterName %s valueParameterString %s valueParameterDouble %f behaviorId %i actionIndex %i stripId %i stateId %i", m_Action.GetType().c_str(), m_Action.GetValueParameterName().c_str(), m_Action.GetValueParameterString().c_str(), m_Action.GetValueParameterDouble(), m_BehaviorId, m_ActionIndex, m_ActionContext.GetStripId(), m_ActionContext.GetStateId()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.h index aa34940b..cfa9dd4d 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.h @@ -13,14 +13,18 @@ class AMFArrayValue; */ class UpdateActionMessage : public BehaviorMessageBase { public: - UpdateActionMessage(AMFArrayValue* arguments); - int32_t GetActionIndex() const { return actionIndex; }; - ActionContext GetActionContext() const { return actionContext; }; - Action GetAction() const { return action; }; + UpdateActionMessage(const AMFArrayValue* arguments); + + [[nodiscard]] int32_t GetActionIndex() const noexcept { return m_ActionIndex; } + + [[nodiscard]] const ActionContext& GetActionContext() const noexcept { return m_ActionContext; } + + [[nodiscard]] const Action& GetAction() const noexcept { return m_Action; } + private: - int32_t actionIndex; - ActionContext actionContext; - Action action; + int32_t m_ActionIndex; + ActionContext m_ActionContext; + Action m_Action; }; #endif //!__UPDATEACTIONMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp index 05dc7cf7..593673b6 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp @@ -1,8 +1,9 @@ #include "UpdateStripUiMessage.h" -UpdateStripUiMessage::UpdateStripUiMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - position = StripUiPosition(arguments); - actionContext = ActionContext(arguments); +UpdateStripUiMessage::UpdateStripUiMessage(const AMFArrayValue* arguments) + : BehaviorMessageBase{ arguments } + , m_Position{ arguments } + , m_ActionContext{ arguments } { - LOG_DEBUG("xPosition %f yPosition %f stripId %i stateId %i behaviorId %i", position.GetX(), position.GetY(), actionContext.GetStripId(), actionContext.GetStateId(), behaviorId); + LOG_DEBUG("xPosition %f yPosition %f stripId %i stateId %i behaviorId %i", m_Position.GetX(), m_Position.GetY(), m_ActionContext.GetStripId(), m_ActionContext.GetStateId(), m_BehaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.h index 0e9afe81..85ca5d54 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.h @@ -13,12 +13,15 @@ class AMFArrayValue; */ class UpdateStripUiMessage : public BehaviorMessageBase { public: - UpdateStripUiMessage(AMFArrayValue* arguments); - StripUiPosition GetPosition() const { return position; }; - ActionContext GetActionContext() const { return actionContext; }; + UpdateStripUiMessage(const AMFArrayValue* arguments); + + [[nodiscard]] const StripUiPosition& GetPosition() const noexcept { return m_Position; }; + + [[nodiscard]] const ActionContext& GetActionContext() const noexcept { return m_ActionContext; }; + private: - StripUiPosition position; - ActionContext actionContext; + StripUiPosition m_Position; + ActionContext m_ActionContext; }; #endif //!__UPDATESTRIPUIMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviors.cpp b/dGame/dPropertyBehaviors/ControlBehaviors.cpp index 5fee358d..c4d22482 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviors.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviors.cpp @@ -63,7 +63,7 @@ void ControlBehaviors::SendBehaviorListToClient(const ControlBehaviorContext& co // TODO This is also supposed to serialize the state of the behaviors in progress but those aren't implemented yet void ControlBehaviors::SendBehaviorBlocksToClient(ControlBehaviorContext& context) { if (!context) return; - BehaviorMessageBase behaviorMsg(context.arguments); + BehaviorMessageBase behaviorMsg{ context.arguments }; context.modelComponent->VerifyBehaviors(); AMFArrayValue behavior; @@ -71,8 +71,8 @@ void ControlBehaviors::SendBehaviorBlocksToClient(ControlBehaviorContext& contex GameMessages::SendUIMessageServerToSingleClient(context.modelOwner, context.modelOwner->GetSystemAddress(), "UpdateBehaviorBlocks", behavior); } -void ControlBehaviors::UpdateAction(AMFArrayValue* arguments) { - UpdateActionMessage updateActionMessage(arguments); +void ControlBehaviors::UpdateAction(const AMFArrayValue* arguments) { + UpdateActionMessage updateActionMessage{ arguments }; auto blockDefinition = GetBlockInfo(updateActionMessage.GetAction().GetType()); if (!blockDefinition) { @@ -95,18 +95,18 @@ void ControlBehaviors::UpdateAction(AMFArrayValue* arguments) { } } -void ControlBehaviors::ProcessCommand(Entity* modelEntity, const SystemAddress& sysAddr, AMFArrayValue* arguments, std::string command, Entity* modelOwner) { +void ControlBehaviors::ProcessCommand(Entity* modelEntity, AMFArrayValue* arguments, std::string& command, Entity* modelOwner) { if (!isInitialized || !modelEntity || !modelOwner || !arguments) return; - auto* modelComponent = modelEntity->GetComponent(); + auto* const modelComponent = modelEntity->GetComponent(); if (!modelComponent) return; - ControlBehaviorContext context(arguments, modelComponent, modelOwner); + ControlBehaviorContext context{ arguments, modelComponent, modelOwner }; if (command == "sendBehaviorListToClient") { SendBehaviorListToClient(context); } else if (command == "modelTypeChanged") { - auto* modelType = arguments->Get("ModelType"); + auto* const modelType = arguments->Get("ModelType"); if (!modelType) return; modelEntity->SetVar(u"modelType", modelType->GetValue()); @@ -131,7 +131,7 @@ void ControlBehaviors::ProcessCommand(Entity* modelEntity, const SystemAddress& } else if (command == "rearrangeStrip") { context.modelComponent->HandleControlBehaviorsMsg(arguments); } else if (command == "add") { - AddMessage msg(context.arguments); + AddMessage msg{ context.arguments }; context.modelComponent->AddBehavior(msg); SendBehaviorListToClient(context); } else if (command == "removeActions") { @@ -144,7 +144,7 @@ void ControlBehaviors::ProcessCommand(Entity* modelEntity, const SystemAddress& } else if (command == "sendBehaviorBlocksToClient") { SendBehaviorBlocksToClient(context); } else if (command == "moveToInventory") { - MoveToInventoryMessage msg(arguments); + MoveToInventoryMessage msg{ arguments }; context.modelComponent->MoveToInventory(msg); auto* characterComponent = modelOwner->GetComponent(); if (!characterComponent) return; @@ -239,7 +239,7 @@ ControlBehaviors::ControlBehaviors() { if (values) { auto* value = values->FirstChildElement("Value"); while (value) { - if (value->GetText() == blockDefinition.GetDefaultValue()) blockDefinition.GetDefaultValue() = std::to_string(blockDefinition.GetMaximumValue()); + if (value->GetText() == blockDefinition.GetDefaultValue()) blockDefinition.SetDefaultValue(std::to_string(blockDefinition.GetMaximumValue())); blockDefinition.SetMaximumValue(blockDefinition.GetMaximumValue() + 1); value = value->NextSiblingElement("Value"); } @@ -283,7 +283,7 @@ ControlBehaviors::ControlBehaviors() { } } -std::optional ControlBehaviors::GetBlockInfo(const BlockName& blockName) { +std::optional ControlBehaviors::GetBlockInfo(const std::string& blockName) { auto blockDefinition = blockTypes.find(blockName); return blockDefinition != blockTypes.end() ? std::optional(blockDefinition->second) : std::nullopt; } diff --git a/dGame/dPropertyBehaviors/ControlBehaviors.h b/dGame/dPropertyBehaviors/ControlBehaviors.h index ab739408..4eab5367 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviors.h +++ b/dGame/dPropertyBehaviors/ControlBehaviors.h @@ -19,15 +19,17 @@ class SystemAddress; typedef std::string BlockName; //! A block name struct ControlBehaviorContext { - ControlBehaviorContext(AMFArrayValue* args, ModelComponent* modelComponent, Entity* modelOwner) : arguments(args), modelComponent(modelComponent), modelOwner(modelOwner) {}; + ControlBehaviorContext(AMFArrayValue* args, ModelComponent* modelComponent, Entity* modelOwner) noexcept + : arguments{ args }, modelComponent{ modelComponent }, modelOwner{ modelOwner } { + }; operator bool() const { return arguments != nullptr && modelComponent != nullptr && modelOwner != nullptr; } AMFArrayValue* arguments; - Entity* modelOwner; ModelComponent* modelComponent; + Entity* modelOwner; }; class ControlBehaviors: public Singleton { @@ -37,12 +39,11 @@ public: * @brief Main driver for processing Property Behavior commands * * @param modelEntity The model that sent this command - * @param sysAddr The SystemAddress to respond to * @param arguments The arguments formatted as an AMFArrayValue * @param command The command to perform * @param modelOwner The owner of the model which sent this command */ - void ProcessCommand(Entity* modelEntity, const SystemAddress& sysAddr, AMFArrayValue* arguments, std::string command, Entity* modelOwner); + void ProcessCommand(Entity* modelEntity, AMFArrayValue* arguments, std::string& command, Entity* modelOwner); /** * @brief Gets a blocks parameter values by the name @@ -52,13 +53,13 @@ public: * * @return A pair of the block parameter name to its typing */ - std::optional GetBlockInfo(const BlockName& blockName); + [[nodiscard]] std::optional GetBlockInfo(const std::string& blockName); private: void RequestUpdatedID(ControlBehaviorContext& context); void SendBehaviorListToClient(const ControlBehaviorContext& context); void SendBehaviorBlocksToClient(ControlBehaviorContext& context); - void UpdateAction(AMFArrayValue* arguments); - std::map blockTypes{}; + void UpdateAction(const AMFArrayValue* arguments); + std::map> blockTypes{}; // If false, property behaviors will not be able to be edited. bool isInitialized = false; diff --git a/dGame/dPropertyBehaviors/PropertyBehavior.cpp b/dGame/dPropertyBehaviors/PropertyBehavior.cpp index f6f6e4f1..423751c4 100644 --- a/dGame/dPropertyBehaviors/PropertyBehavior.cpp +++ b/dGame/dPropertyBehaviors/PropertyBehavior.cpp @@ -83,10 +83,6 @@ void PropertyBehavior::HandleMsg(AddMessage& msg) { isLoot = m_BehaviorId != 7965; }; -void PropertyBehavior::SetBehaviorId(int32_t behaviorId) { - m_BehaviorId = behaviorId; -} - void PropertyBehavior::SendBehaviorListToClient(AMFArrayValue& args) const { args.Insert("id", std::to_string(m_BehaviorId)); args.Insert("name", m_Name); @@ -111,19 +107,18 @@ void PropertyBehavior::VerifyLastEditedState() { } void PropertyBehavior::SendBehaviorBlocksToClient(AMFArrayValue& args) const { - auto* stateArray = args.InsertArray("states"); + auto* const stateArray = args.InsertArray("states"); - auto lastState = BehaviorState::HOME_STATE; - for (auto& [stateId, state] : m_States) { + for (const auto& [stateId, state] : m_States) { if (state.IsEmpty()) continue; LOG_DEBUG("Serializing state %i", stateId); - auto* stateArgs = stateArray->PushArray(); + auto* const stateArgs = stateArray->PushArray(); stateArgs->Insert("id", static_cast(stateId)); state.SendBehaviorBlocksToClient(*stateArgs); } - auto* executionState = args.InsertArray("executionState"); + auto* const executionState = args.InsertArray("executionState"); executionState->Insert("stateID", static_cast(m_LastEditedState)); executionState->InsertArray("strips"); diff --git a/dGame/dPropertyBehaviors/PropertyBehavior.h b/dGame/dPropertyBehaviors/PropertyBehavior.h index dc53bbed..c9cb4b98 100644 --- a/dGame/dPropertyBehaviors/PropertyBehavior.h +++ b/dGame/dPropertyBehaviors/PropertyBehavior.h @@ -13,7 +13,8 @@ class AMFArrayValue; class PropertyBehavior { public: PropertyBehavior(); - template + + template void HandleMsg(Msg& msg); // If the last edited state has no strips, this method will set the last edited state to the first state that has strips. @@ -21,8 +22,9 @@ public: void SendBehaviorListToClient(AMFArrayValue& args) const; void SendBehaviorBlocksToClient(AMFArrayValue& args) const; - int32_t GetBehaviorId() const { return m_BehaviorId; } - void SetBehaviorId(int32_t id); + [[nodiscard]] int32_t GetBehaviorId() const noexcept { return m_BehaviorId; } + void SetBehaviorId(int32_t id) noexcept { m_BehaviorId = id; } + private: // The states this behavior has. diff --git a/dGame/dPropertyBehaviors/State.cpp b/dGame/dPropertyBehaviors/State.cpp index 59a9aa8b..0c8a11d9 100644 --- a/dGame/dPropertyBehaviors/State.cpp +++ b/dGame/dPropertyBehaviors/State.cpp @@ -3,7 +3,7 @@ #include "Amf3.h" #include "ControlBehaviorMsgs.h" -template<> +template <> void State::HandleMsg(AddStripMessage& msg) { if (m_Strips.size() <= msg.GetActionContext().GetStripId()) { m_Strips.resize(msg.GetActionContext().GetStripId() + 1); @@ -11,7 +11,7 @@ void State::HandleMsg(AddStripMessage& msg) { m_Strips.at(msg.GetActionContext().GetStripId()).HandleMsg(msg); }; -template<> +template <> void State::HandleMsg(AddActionMessage& msg) { if (m_Strips.size() <= msg.GetActionContext().GetStripId()) { return; @@ -20,7 +20,7 @@ void State::HandleMsg(AddActionMessage& msg) { m_Strips.at(msg.GetActionContext().GetStripId()).HandleMsg(msg); }; -template<> +template <> void State::HandleMsg(UpdateStripUiMessage& msg) { if (m_Strips.size() <= msg.GetActionContext().GetStripId()) { return; @@ -29,7 +29,7 @@ void State::HandleMsg(UpdateStripUiMessage& msg) { m_Strips.at(msg.GetActionContext().GetStripId()).HandleMsg(msg); }; -template<> +template <> void State::HandleMsg(RemoveActionsMessage& msg) { if (m_Strips.size() <= msg.GetActionContext().GetStripId()) { return; @@ -38,7 +38,7 @@ void State::HandleMsg(RemoveActionsMessage& msg) { m_Strips.at(msg.GetActionContext().GetStripId()).HandleMsg(msg); }; -template<> +template <> void State::HandleMsg(RearrangeStripMessage& msg) { if (m_Strips.size() <= msg.GetActionContext().GetStripId()) { return; @@ -47,7 +47,7 @@ void State::HandleMsg(RearrangeStripMessage& msg) { m_Strips.at(msg.GetActionContext().GetStripId()).HandleMsg(msg); }; -template<> +template <> void State::HandleMsg(UpdateActionMessage& msg) { if (m_Strips.size() <= msg.GetActionContext().GetStripId()) { return; @@ -56,7 +56,7 @@ void State::HandleMsg(UpdateActionMessage& msg) { m_Strips.at(msg.GetActionContext().GetStripId()).HandleMsg(msg); }; -template<> +template <> void State::HandleMsg(RemoveStripMessage& msg) { if (m_Strips.size() <= msg.GetActionContext().GetStripId()) { return; @@ -65,7 +65,7 @@ void State::HandleMsg(RemoveStripMessage& msg) { m_Strips.at(msg.GetActionContext().GetStripId()).HandleMsg(msg); }; -template<> +template <> void State::HandleMsg(SplitStripMessage& msg) { if (msg.GetTransferredActions().empty()) { if (m_Strips.size() <= msg.GetSourceActionContext().GetStripId()) { @@ -82,7 +82,7 @@ void State::HandleMsg(SplitStripMessage& msg) { } }; -template<> +template <> void State::HandleMsg(MergeStripsMessage& msg) { if (msg.GetMigratedActions().empty()) { if (m_Strips.size() <= msg.GetSourceActionContext().GetStripId()) { @@ -99,7 +99,7 @@ void State::HandleMsg(MergeStripsMessage& msg) { } }; -template<> +template <> void State::HandleMsg(MigrateActionsMessage& msg) { if (msg.GetMigratedActions().empty()) { if (m_Strips.size() <= msg.GetSourceActionContext().GetStripId()) { @@ -117,19 +117,19 @@ void State::HandleMsg(MigrateActionsMessage& msg) { }; bool State::IsEmpty() const { - for (auto& strip : m_Strips) { + for (const auto& strip : m_Strips) { if (!strip.IsEmpty()) return false; } return true; } void State::SendBehaviorBlocksToClient(AMFArrayValue& args) const { - auto* strips = args.InsertArray("strips"); - for (int32_t stripId = 0; stripId < m_Strips.size(); stripId++) { - auto& strip = m_Strips.at(stripId); + auto* const strips = args.InsertArray("strips"); + for (size_t stripId = 0; stripId < m_Strips.size(); ++stripId) { + const auto& strip = m_Strips.at(stripId); if (strip.IsEmpty()) continue; - auto* stripArgs = strips->PushArray(); + auto* const stripArgs = strips->PushArray(); stripArgs->Insert("id", static_cast(stripId)); strip.SendBehaviorBlocksToClient(*stripArgs); diff --git a/dGame/dPropertyBehaviors/State.h b/dGame/dPropertyBehaviors/State.h index a6a6d23b..f0425763 100644 --- a/dGame/dPropertyBehaviors/State.h +++ b/dGame/dPropertyBehaviors/State.h @@ -7,11 +7,12 @@ class AMFArrayValue; class State { public: - template + template void HandleMsg(Msg& msg); void SendBehaviorBlocksToClient(AMFArrayValue& args) const; bool IsEmpty() const; + private: std::vector m_Strips; }; diff --git a/dGame/dPropertyBehaviors/Strip.cpp b/dGame/dPropertyBehaviors/Strip.cpp index 7d27cacd..0f459e46 100644 --- a/dGame/dPropertyBehaviors/Strip.cpp +++ b/dGame/dPropertyBehaviors/Strip.cpp @@ -3,48 +3,47 @@ #include "Amf3.h" #include "ControlBehaviorMsgs.h" -template<> +template <> void Strip::HandleMsg(AddStripMessage& msg) { m_Actions = msg.GetActionsToAdd(); m_Position = msg.GetPosition(); }; -template<> +template <> void Strip::HandleMsg(AddActionMessage& msg) { if (msg.GetActionIndex() == -1) return; - m_Actions.insert(m_Actions.begin() + msg.GetActionIndex(), msg.GetAction()); }; -template<> +template <> void Strip::HandleMsg(UpdateStripUiMessage& msg) { m_Position = msg.GetPosition(); }; -template<> +template <> void Strip::HandleMsg(RemoveStripMessage& msg) { m_Actions.clear(); }; -template<> +template <> void Strip::HandleMsg(RemoveActionsMessage& msg) { if (msg.GetActionIndex() >= m_Actions.size()) return; m_Actions.erase(m_Actions.begin() + msg.GetActionIndex(), m_Actions.end()); }; -template<> +template <> void Strip::HandleMsg(UpdateActionMessage& msg) { if (msg.GetActionIndex() >= m_Actions.size()) return; m_Actions.at(msg.GetActionIndex()) = msg.GetAction(); }; -template<> +template <> void Strip::HandleMsg(RearrangeStripMessage& msg) { if (msg.GetDstActionIndex() >= m_Actions.size() || msg.GetSrcActionIndex() >= m_Actions.size() || msg.GetSrcActionIndex() <= msg.GetDstActionIndex()) return; std::rotate(m_Actions.begin() + msg.GetDstActionIndex(), m_Actions.begin() + msg.GetSrcActionIndex(), m_Actions.end()); }; -template<> +template <> void Strip::HandleMsg(SplitStripMessage& msg) { if (msg.GetTransferredActions().empty() && !m_Actions.empty()) { auto startToMove = m_Actions.begin() + msg.GetSrcActionIndex(); @@ -56,7 +55,7 @@ void Strip::HandleMsg(SplitStripMessage& msg) { } }; -template<> +template <> void Strip::HandleMsg(MergeStripsMessage& msg) { if (msg.GetMigratedActions().empty() && !m_Actions.empty()) { msg.SetMigratedActions(m_Actions.begin(), m_Actions.end()); @@ -66,7 +65,7 @@ void Strip::HandleMsg(MergeStripsMessage& msg) { } }; -template<> +template <> void Strip::HandleMsg(MigrateActionsMessage& msg) { if (msg.GetMigratedActions().empty() && !m_Actions.empty()) { auto startToMove = m_Actions.begin() + msg.GetSrcActionIndex(); @@ -80,8 +79,8 @@ void Strip::HandleMsg(MigrateActionsMessage& msg) { void Strip::SendBehaviorBlocksToClient(AMFArrayValue& args) const { m_Position.SendBehaviorBlocksToClient(args); - auto* actions = args.InsertArray("actions"); - for (auto& action : m_Actions) { + auto* const actions = args.InsertArray("actions"); + for (const auto& action : m_Actions) { action.SendBehaviorBlocksToClient(*actions); } }; diff --git a/dGame/dPropertyBehaviors/Strip.h b/dGame/dPropertyBehaviors/Strip.h index f3e10964..107fee11 100644 --- a/dGame/dPropertyBehaviors/Strip.h +++ b/dGame/dPropertyBehaviors/Strip.h @@ -10,11 +10,12 @@ class AMFArrayValue; class Strip { public: - template + template void HandleMsg(Msg& msg); void SendBehaviorBlocksToClient(AMFArrayValue& args) const; - bool IsEmpty() const { return m_Actions.empty(); } + bool IsEmpty() const noexcept { return m_Actions.empty(); } + private: std::vector m_Actions; StripUiPosition m_Position; From f38537aece7a63d541ae5d93c1fc43d2269734ad Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 20 Feb 2024 03:51:02 -0800 Subject: [PATCH 24/50] fix: incorrectly inverted statement (#1459) if we DONT find it, we want to kill/delete it. not the other way around where if we find it we try to delete it again. tested that you no longer crash when trying to login tested that bird monument issues are fixed --- dGame/EntityManager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index fc9fa0f0..9cd9df43 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -575,13 +575,13 @@ void EntityManager::ScheduleForKill(Entity* entity) { const auto objectId = entity->GetObjectID(); - if (std::find(m_EntitiesToKill.begin(), m_EntitiesToKill.end(), objectId) != m_EntitiesToKill.end()) { + if (std::find(m_EntitiesToKill.begin(), m_EntitiesToKill.end(), objectId) == m_EntitiesToKill.end()) { m_EntitiesToKill.push_back(objectId); } } void EntityManager::ScheduleForDeletion(LWOOBJID entity) { - if (std::find(m_EntitiesToDelete.begin(), m_EntitiesToDelete.end(), entity) != m_EntitiesToDelete.end()) { + if (std::find(m_EntitiesToDelete.begin(), m_EntitiesToDelete.end(), entity) == m_EntitiesToDelete.end()) { m_EntitiesToDelete.push_back(entity); } } From 5ae8fd8e0e7088dc125819fd47f9184074a2be80 Mon Sep 17 00:00:00 2001 From: jadebenn Date: Sat, 24 Feb 2024 04:30:02 -0600 Subject: [PATCH 25/50] chore: Remove anonymous namespace from GeneralUtils.h (#1460) * remove anonymous namespace from GeneralUtils.h * Put helper functions in nested details namespace to hide from hinting * rename implementation functions to use lower case, leading underscore and move definitions to source file --- dCommon/GeneralUtils.cpp | 50 +++++++++++++++++++++++++++++----------- dCommon/GeneralUtils.h | 26 +++++---------------- 2 files changed, 42 insertions(+), 34 deletions(-) diff --git a/dCommon/GeneralUtils.cpp b/dCommon/GeneralUtils.cpp index 78cf4f48..3e3e2f9c 100644 --- a/dCommon/GeneralUtils.cpp +++ b/dCommon/GeneralUtils.cpp @@ -294,28 +294,50 @@ std::u16string GeneralUtils::ReadWString(RakNet::BitStream* inStream) { std::vector GeneralUtils::GetSqlFileNamesFromFolder(const std::string& folder) { // Because we dont know how large the initial number before the first _ is we need to make it a map like so. - std::map filenames{}; + std::map filenames{}; for (auto& t : std::filesystem::directory_iterator(folder)) { - auto filename = t.path().filename().string(); - auto index = std::stoi(GeneralUtils::SplitString(filename, '_').at(0)); - filenames.insert(std::make_pair(index, filename)); + auto filename = t.path().filename().string(); + auto index = std::stoi(GeneralUtils::SplitString(filename, '_').at(0)); + filenames.insert(std::make_pair(index, filename)); } // Now sort the map by the oldest migration. std::vector sortedFiles{}; - auto fileIterator = filenames.begin(); - std::map::iterator oldest = filenames.begin(); - while (!filenames.empty()) { + auto fileIterator = filenames.begin(); + std::map::iterator oldest = filenames.begin(); + while (!filenames.empty()) { if (fileIterator == filenames.end()) { - sortedFiles.push_back(oldest->second); - filenames.erase(oldest); - fileIterator = filenames.begin(); - oldest = filenames.begin(); - continue; + sortedFiles.push_back(oldest->second); + filenames.erase(oldest); + fileIterator = filenames.begin(); + oldest = filenames.begin(); + continue; } - if (oldest->first > fileIterator->first) oldest = fileIterator; - fileIterator++; + if (oldest->first > fileIterator->first) oldest = fileIterator; + fileIterator++; } return sortedFiles; } + +#ifdef DARKFLAME_PLATFORM_MACOS + +// MacOS floating-point parse function specializations +namespace GeneralUtils::details { + template <> + [[nodiscard]] float _parse(const std::string_view str, size_t& parseNum) { + return std::stof(std::string{ str }, &parseNum); + } + + template <> + [[nodiscard]] double _parse(const std::string_view str, size_t& parseNum) { + return std::stod(std::string{ str }, &parseNum); + } + + template <> + [[nodiscard]] long double _parse(const std::string_view str, size_t& parseNum) { + return std::stold(std::string{ str }, &parseNum); + } +} + +#endif diff --git a/dCommon/GeneralUtils.h b/dCommon/GeneralUtils.h index 15659912..42d84aea 100644 --- a/dCommon/GeneralUtils.h +++ b/dCommon/GeneralUtils.h @@ -168,25 +168,10 @@ namespace GeneralUtils { #ifdef DARKFLAME_PLATFORM_MACOS - // Anonymous namespace containing MacOS floating-point parse function specializations - namespace { + // MacOS floating-point parse helper function specializations + namespace details { template - [[nodiscard]] T Parse(const std::string_view str, size_t* parseNum); - - template <> - [[nodiscard]] float Parse(const std::string_view str, size_t* parseNum) { - return std::stof(std::string{ str }, parseNum); - } - - template <> - [[nodiscard]] double Parse(const std::string_view str, size_t* parseNum) { - return std::stod(std::string{ str }, parseNum); - } - - template <> - [[nodiscard]] long double Parse(const std::string_view str, size_t* parseNum) { - return std::stold(std::string{ str }, parseNum); - } + [[nodiscard]] T _parse(const std::string_view str, size_t& parseNum); } /** @@ -196,9 +181,10 @@ namespace GeneralUtils { * @returns An std::optional containing the desired value if it is equivalent to the string */ template - [[nodiscard]] std::optional TryParse(const std::string_view str) noexcept try { + [[nodiscard]] std::optional TryParse(const std::string_view str) noexcept + try { size_t parseNum; - const T result = Parse(str, &parseNum); + const T result = details::_parse(str, parseNum); const bool isParsed = str.length() == parseNum; return isParsed ? result : std::optional{}; From 721ea78bb47d11551b82c14630c1c4a2e41da618 Mon Sep 17 00:00:00 2001 From: jadebenn Date: Sat, 24 Feb 2024 23:03:59 -0600 Subject: [PATCH 26/50] Update Amf3.h member naming scheme (#1463) --- dCommon/Amf3.h | 100 ++++++++++++++++++++++++------------------------- 1 file changed, 49 insertions(+), 51 deletions(-) diff --git a/dCommon/Amf3.h b/dCommon/Amf3.h index c3077370..294a5b6c 100644 --- a/dCommon/Amf3.h +++ b/dCommon/Amf3.h @@ -41,12 +41,13 @@ template class AMFValue : public AMFBaseValue { public: AMFValue() = default; - AMFValue(const ValueType value) { m_Data = value; } + AMFValue(const ValueType value) : m_Data{ value } {} virtual ~AMFValue() override = default; [[nodiscard]] constexpr eAmf GetValueType() const noexcept override; [[nodiscard]] const ValueType& GetValue() const { return m_Data; } + void SetValue(const ValueType value) { m_Data = value; } protected: @@ -54,7 +55,7 @@ protected: }; // Explicit template class instantiations -template class AMFValue; +template class AMFValue; template class AMFValue; template class AMFValue; template class AMFValue; @@ -110,7 +111,7 @@ public: [[nodiscard]] constexpr eAmf GetValueType() const noexcept override { return eAmf::Array; } ~AMFArrayValue() override { - for (auto valueToDelete : GetDense()) { + for (const auto* valueToDelete : GetDense()) { if (valueToDelete) { delete valueToDelete; valueToDelete = nullptr; @@ -127,12 +128,12 @@ public: /** * Returns the Associative portion of the object */ - [[nodiscard]] inline const AMFAssociative& GetAssociative() const noexcept { return this->associative; } + [[nodiscard]] inline const AMFAssociative& GetAssociative() const noexcept { return m_Associative; } /** * Returns the dense portion of the object */ - [[nodiscard]] inline const AMFDense& GetDense() const noexcept { return this->dense; } + [[nodiscard]] inline const AMFDense& GetDense() const noexcept { return m_Dense; } /** * Inserts an AMFValue into the associative portion with the given key. @@ -150,12 +151,12 @@ public: */ template [[maybe_unused]] std::pair*, bool> Insert(const std::string& key, const ValueType value) { - auto element = associative.find(key); + const auto element = m_Associative.find(key); AMFValue* val = nullptr; bool found = true; - if (element == associative.end()) { + if (element == m_Associative.cend()) { val = new AMFValue(value); - associative.insert(std::make_pair(key, val)); + m_Associative.emplace(key, val); } else { val = dynamic_cast*>(element->second); found = false; @@ -165,12 +166,12 @@ public: // Associates an array with a string key [[maybe_unused]] std::pair Insert(const std::string& key) { - auto element = associative.find(key); + const auto element = m_Associative.find(key); AMFArrayValue* val = nullptr; bool found = true; - if (element == associative.end()) { + if (element == m_Associative.cend()) { val = new AMFArrayValue(); - associative.insert(std::make_pair(key, val)); + m_Associative.emplace(key, val); } else { val = dynamic_cast(element->second); found = false; @@ -182,13 +183,13 @@ public: [[maybe_unused]] std::pair Insert(const size_t index) { AMFArrayValue* val = nullptr; bool inserted = false; - if (index >= dense.size()) { - dense.resize(index + 1); + if (index >= m_Dense.size()) { + m_Dense.resize(index + 1); val = new AMFArrayValue(); - dense.at(index) = val; + m_Dense.at(index) = val; inserted = true; } - return std::make_pair(dynamic_cast(dense.at(index)), inserted); + return std::make_pair(dynamic_cast(m_Dense.at(index)), inserted); } /** @@ -205,13 +206,13 @@ public: [[maybe_unused]] std::pair*, bool> Insert(const size_t index, const ValueType value) { AMFValue* val = nullptr; bool inserted = false; - if (index >= this->dense.size()) { - this->dense.resize(index + 1); + if (index >= m_Dense.size()) { + m_Dense.resize(index + 1); val = new AMFValue(value); - this->dense.at(index) = val; + m_Dense.at(index) = val; inserted = true; } - return std::make_pair(dynamic_cast*>(this->dense.at(index)), inserted); + return std::make_pair(dynamic_cast*>(m_Dense.at(index)), inserted); } /** @@ -224,12 +225,12 @@ public: * @param value The value to insert */ void Insert(const std::string& key, AMFBaseValue* const value) { - auto element = associative.find(key); - if (element != associative.end() && element->second) { + const auto element = m_Associative.find(key); + if (element != m_Associative.cend() && element->second) { delete element->second; element->second = value; } else { - associative.insert(std::make_pair(key, value)); + m_Associative.emplace(key, value); } } @@ -243,13 +244,13 @@ public: * @param value The value to insert */ void Insert(const size_t index, AMFBaseValue* const value) { - if (index < dense.size()) { - AMFDense::iterator itr = dense.begin() + index; - if (*itr) delete dense.at(index); + if (index < m_Dense.size()) { + const AMFDense::const_iterator itr = m_Dense.cbegin() + index; + if (*itr) delete m_Dense.at(index); } else { - dense.resize(index + 1); + m_Dense.resize(index + 1); } - dense.at(index) = value; + m_Dense.at(index) = value; } /** @@ -264,7 +265,7 @@ public: */ template [[maybe_unused]] inline AMFValue* Push(const ValueType value) { - return Insert(this->dense.size(), value).first; + return Insert(m_Dense.size(), value).first; } /** @@ -275,10 +276,10 @@ public: * @param key The key to remove from the associative portion */ void Remove(const std::string& key, const bool deleteValue = true) { - AMFAssociative::iterator it = this->associative.find(key); - if (it != this->associative.end()) { + const AMFAssociative::const_iterator it = m_Associative.find(key); + if (it != m_Associative.cend()) { if (deleteValue) delete it->second; - this->associative.erase(it); + m_Associative.erase(it); } } @@ -286,27 +287,24 @@ public: * Pops the last element in the dense portion, deleting it in the process. */ void Remove(const size_t index) { - if (!this->dense.empty() && index < this->dense.size()) { - auto itr = this->dense.begin() + index; + if (!m_Dense.empty() && index < m_Dense.size()) { + const auto itr = m_Dense.cbegin() + index; if (*itr) delete (*itr); - this->dense.erase(itr); + m_Dense.erase(itr); } } void Pop() { - if (!this->dense.empty()) Remove(this->dense.size() - 1); + if (!m_Dense.empty()) Remove(m_Dense.size() - 1); } [[nodiscard]] AMFArrayValue* GetArray(const std::string& key) const { - AMFAssociative::const_iterator it = this->associative.find(key); - if (it != this->associative.end()) { - return dynamic_cast(it->second); - } - return nullptr; + const AMFAssociative::const_iterator it = m_Associative.find(key); + return it != m_Associative.cend() ? dynamic_cast(it->second) : nullptr; } [[nodiscard]] AMFArrayValue* GetArray(const size_t index) const { - return index >= this->dense.size() ? nullptr : dynamic_cast(this->dense.at(index)); + return index < m_Dense.size() ? dynamic_cast(m_Dense.at(index)) : nullptr; } [[maybe_unused]] inline AMFArrayValue* InsertArray(const std::string& key) { @@ -318,7 +316,7 @@ public: } [[maybe_unused]] inline AMFArrayValue* PushArray() { - return static_cast(Insert(this->dense.size()).first); + return static_cast(Insert(m_Dense.size()).first); } /** @@ -332,16 +330,16 @@ public: */ template [[nodiscard]] AMFValue* Get(const std::string& key) const { - AMFAssociative::const_iterator it = this->associative.find(key); - return it != this->associative.end() ? + const AMFAssociative::const_iterator it = m_Associative.find(key); + return it != m_Associative.cend() ? dynamic_cast*>(it->second) : nullptr; } // Get from the array but dont cast it [[nodiscard]] AMFBaseValue* Get(const std::string& key) const { - AMFAssociative::const_iterator it = this->associative.find(key); - return it != this->associative.end() ? it->second : nullptr; + const AMFAssociative::const_iterator it = m_Associative.find(key); + return it != m_Associative.cend() ? it->second : nullptr; } /** @@ -355,27 +353,27 @@ public: */ template [[nodiscard]] AMFValue* Get(const size_t index) const { - return index < this->dense.size() ? - dynamic_cast*>(this->dense.at(index)) : + return index < m_Dense.size() ? + dynamic_cast*>(m_Dense.at(index)) : nullptr; } // Get from the dense but dont cast it [[nodiscard]] AMFBaseValue* Get(const size_t index) const { - return index < this->dense.size() ? this->dense.at(index) : nullptr; + return index < m_Dense.size() ? m_Dense.at(index) : nullptr; } private: /** * The associative portion. These values are key'd with strings to an AMFValue. */ - AMFAssociative associative; + AMFAssociative m_Associative; /** * The dense portion. These AMFValue's are stored one after * another with the most recent addition being at the back. */ - AMFDense dense; + AMFDense m_Dense; }; #endif //!__AMF3__H__ From 1328850a8d225d969784fb6b59fe282e4e019915 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 24 Feb 2024 23:01:28 -0800 Subject: [PATCH 27/50] buffRemoval (#1464) Update BuffComponent.cpp --- dGame/dComponents/BuffComponent.cpp | 7 +++---- dGame/dComponents/BuffComponent.h | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/dGame/dComponents/BuffComponent.cpp b/dGame/dComponents/BuffComponent.cpp index cdf1d5bc..4122a800 100644 --- a/dGame/dComponents/BuffComponent.cpp +++ b/dGame/dComponents/BuffComponent.cpp @@ -208,9 +208,8 @@ void BuffComponent::ApplyBuff(const int32_t id, const float duration, const LWOO void BuffComponent::RemoveBuff(int32_t id, bool fromUnEquip, bool removeImmunity, bool ignoreRefCount) { const auto& iter = m_Buffs.find(id); - if (iter == m_Buffs.end()) { - return; - } + // If the buff is already scheduled to be removed, don't do it again + if (iter == m_Buffs.end() || m_BuffsToRemove.contains(id)) return; if (!ignoreRefCount && !iter->second.cancelOnRemoveBuff) { iter->second.refCount--; @@ -222,7 +221,7 @@ void BuffComponent::RemoveBuff(int32_t id, bool fromUnEquip, bool removeImmunity GameMessages::SendRemoveBuff(m_Parent, fromUnEquip, removeImmunity, id); - m_BuffsToRemove.push_back(id); + m_BuffsToRemove.insert(id); RemoveBuffEffect(id); } diff --git a/dGame/dComponents/BuffComponent.h b/dGame/dComponents/BuffComponent.h index 18aa7a42..f509faa2 100644 --- a/dGame/dComponents/BuffComponent.h +++ b/dGame/dComponents/BuffComponent.h @@ -141,7 +141,7 @@ private: std::map m_Buffs; // Buffs to remove at the end of the update frame. - std::vector m_BuffsToRemove; + std::set m_BuffsToRemove; /** * Parameters (=effects) for each buff From e729c7f84659029a0777f409f2f146697797ab81 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Sun, 25 Feb 2024 01:47:05 -0600 Subject: [PATCH 28/50] feat: achievement vendor and vendor feedback (#1461) * Groundwork * movie buying logic out of gm handler make transaction result more useful * Full implementation Cleanup and fix some calls in gamemessages * Load the component in the entity Patch Auth * new line at eof * cache lookups * remove sort * fix includes --- dCommon/dEnums/eReplicaComponentType.h | 2 +- dCommon/dEnums/eVendorTransactionResult.h | 15 +++ .../CDClientTables/CDMissionsTable.cpp | 10 +- .../CDClientTables/CDMissionsTable.h | 3 + dGame/Entity.cpp | 8 ++ .../AchievementVendorComponent.cpp | 72 +++++++++++ .../dComponents/AchievementVendorComponent.h | 23 ++++ dGame/dComponents/CMakeLists.txt | 1 + dGame/dComponents/VendorComponent.cpp | 62 +++++++++ dGame/dComponents/VendorComponent.h | 1 + dGame/dGameMessages/GameMessages.cpp | 121 ++++-------------- dGame/dGameMessages/GameMessages.h | 3 +- dNet/AuthPackets.cpp | 2 +- 13 files changed, 226 insertions(+), 97 deletions(-) create mode 100644 dCommon/dEnums/eVendorTransactionResult.h create mode 100644 dGame/dComponents/AchievementVendorComponent.cpp create mode 100644 dGame/dComponents/AchievementVendorComponent.h diff --git a/dCommon/dEnums/eReplicaComponentType.h b/dCommon/dEnums/eReplicaComponentType.h index 83acbf89..2b991dfb 100644 --- a/dCommon/dEnums/eReplicaComponentType.h +++ b/dCommon/dEnums/eReplicaComponentType.h @@ -106,7 +106,7 @@ enum class eReplicaComponentType : uint32_t { INTERACTION_MANAGER, DONATION_VENDOR, COMBAT_MEDIATOR, - COMMENDATION_VENDOR, + ACHIEVEMENT_VENDOR, GATE_RUSH_CONTROL, RAIL_ACTIVATOR, ROLLER, diff --git a/dCommon/dEnums/eVendorTransactionResult.h b/dCommon/dEnums/eVendorTransactionResult.h new file mode 100644 index 00000000..e61ee0ee --- /dev/null +++ b/dCommon/dEnums/eVendorTransactionResult.h @@ -0,0 +1,15 @@ +#ifndef __EVENDORTRANSACTIONRESULT__ +#define __EVENDORTRANSACTIONRESULT__ + +#include + +enum class eVendorTransactionResult : uint32_t { + SELL_SUCCESS = 0, + SELL_FAIL, + PURCHASE_SUCCESS, + PURCHASE_FAIL, + DONATION_FAIL, + DONATION_FULL +}; + +#endif // !__EVENDORTRANSACTIONRESULT__ diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp index 8862b1db..97dcde9f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp @@ -79,7 +79,6 @@ void CDMissionsTable::LoadValuesFromDatabase() { entries.push_back(entry); tableData.nextRow(); } - tableData.finalize(); Default.id = -1; @@ -118,3 +117,12 @@ const CDMissions& CDMissionsTable::GetByMissionID(uint32_t missionID, bool& foun return Default; } +const std::set CDMissionsTable::GetMissionsForReward(LOT lot) { + std::set toReturn {}; + for (const auto& entry : GetEntries()) { + if (lot == entry.reward_item1 || lot == entry.reward_item2 || lot == entry.reward_item3 || lot == entry.reward_item4) { + toReturn.insert(entry.id); + } + } + return toReturn; +} diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h index 6ba7b19e..5067f2e2 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h @@ -70,6 +70,9 @@ public: const CDMissions& GetByMissionID(uint32_t missionID, bool& found) const; + const std::set GetMissionsForReward(LOT lot); + + static CDMissions Default; }; diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 269b4cc4..bb932991 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -82,6 +82,7 @@ #include "CollectibleComponent.h" #include "ItemComponent.h" #include "GhostComponent.h" +#include "AchievementVendorComponent.h" // Table includes #include "CDComponentsRegistryTable.h" @@ -615,6 +616,8 @@ void Entity::Initialize() { AddComponent(); } else if ((compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::DONATION_VENDOR, -1) != -1)) { AddComponent(); + } else if ((compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::ACHIEVEMENT_VENDOR, -1) != -1)) { + AddComponent(); } if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::PROPERTY_VENDOR, -1) != -1) { @@ -1191,6 +1194,11 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType donationVendorComponent->Serialize(outBitStream, bIsInitialUpdate); } + AchievementVendorComponent* achievementVendorComponent; + if (TryGetComponent(eReplicaComponentType::ACHIEVEMENT_VENDOR, achievementVendorComponent)) { + achievementVendorComponent->Serialize(outBitStream, bIsInitialUpdate); + } + BouncerComponent* bouncerComponent; if (TryGetComponent(eReplicaComponentType::BOUNCER, bouncerComponent)) { bouncerComponent->Serialize(outBitStream, bIsInitialUpdate); diff --git a/dGame/dComponents/AchievementVendorComponent.cpp b/dGame/dComponents/AchievementVendorComponent.cpp new file mode 100644 index 00000000..10a0ca29 --- /dev/null +++ b/dGame/dComponents/AchievementVendorComponent.cpp @@ -0,0 +1,72 @@ +#include "AchievementVendorComponent.h" +#include "MissionComponent.h" +#include "InventoryComponent.h" +#include "eMissionState.h" +#include "CDComponentsRegistryTable.h" +#include "CDItemComponentTable.h" +#include "eVendorTransactionResult.h" +#include "CheatDetection.h" +#include "UserManager.h" +#include "CDMissionsTable.h" + +bool AchievementVendorComponent::SellsItem(Entity* buyer, const LOT lot) { + auto* missionComponent = buyer->GetComponent(); + if (!missionComponent) return false; + + if (m_PlayerPurchasableItems[buyer->GetObjectID()].contains(lot)){ + return true; + } + + CDMissionsTable* missionsTable = CDClientManager::GetTable(); + const auto missions = missionsTable->GetMissionsForReward(lot); + for (const auto mission : missions) { + if (missionComponent->GetMissionState(mission) == eMissionState::COMPLETE) { + m_PlayerPurchasableItems[buyer->GetObjectID()].insert(lot); + return true; + } + } + return false; +} + +void AchievementVendorComponent::Buy(Entity* buyer, LOT lot, uint32_t count) { + // get the item Comp from the item LOT + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); + int itemCompID = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::ITEM); + CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); + uint32_t costLOT = itemComp.commendationLOT; + + if (costLOT == -1 || !SellsItem(buyer, lot)) { + auto* user = UserManager::Instance()->GetUser(buyer->GetSystemAddress()); + CheatDetection::ReportCheat(user, buyer->GetSystemAddress(), "Attempted to buy item %i from achievement vendor %i that is not purchasable", lot, m_Parent->GetLOT()); + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL); + return; + } + + auto* inventoryComponent = buyer->GetComponent(); + if (!inventoryComponent) { + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL); + return; + } + + if (costLOT == 13763) { // Faction Token Proxy + auto* missionComponent = buyer->GetComponent(); + if (!missionComponent) return; + + if (missionComponent->GetMissionState(545) == eMissionState::COMPLETE) costLOT = 8318; // "Assembly Token" + if (missionComponent->GetMissionState(556) == eMissionState::COMPLETE) costLOT = 8321; // "Venture League Token" + if (missionComponent->GetMissionState(567) == eMissionState::COMPLETE) costLOT = 8319; // "Sentinels Token" + if (missionComponent->GetMissionState(578) == eMissionState::COMPLETE) costLOT = 8320; // "Paradox Token" + } + + const uint32_t altCurrencyCost = itemComp.commendationCost * count; + if (inventoryComponent->GetLotCount(costLOT) < altCurrencyCost) { + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL); + return; + } + + inventoryComponent->RemoveItem(costLOT, altCurrencyCost); + inventoryComponent->AddItem(lot, count, eLootSourceType::VENDOR); + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_SUCCESS); + +} \ No newline at end of file diff --git a/dGame/dComponents/AchievementVendorComponent.h b/dGame/dComponents/AchievementVendorComponent.h new file mode 100644 index 00000000..bffd3983 --- /dev/null +++ b/dGame/dComponents/AchievementVendorComponent.h @@ -0,0 +1,23 @@ +#ifndef __ACHIEVEMENTVENDORCOMPONENT__H__ +#define __ACHIEVEMENTVENDORCOMPONENT__H__ + +#include "VendorComponent.h" +#include "eReplicaComponentType.h" +#include +#include + +class Entity; + +class AchievementVendorComponent final : public VendorComponent { +public: + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::ACHIEVEMENT_VENDOR; + AchievementVendorComponent(Entity* parent) : VendorComponent(parent) {}; + bool SellsItem(Entity* buyer, const LOT lot); + void Buy(Entity* buyer, LOT lot, uint32_t count); + +private: + std::map> m_PlayerPurchasableItems; +}; + + +#endif //!__ACHIEVEMENTVENDORCOMPONENT__H__ diff --git a/dGame/dComponents/CMakeLists.txt b/dGame/dComponents/CMakeLists.txt index ac509e11..21fe9207 100644 --- a/dGame/dComponents/CMakeLists.txt +++ b/dGame/dComponents/CMakeLists.txt @@ -1,4 +1,5 @@ set(DGAME_DCOMPONENTS_SOURCES + "AchievementVendorComponent.cpp" "ActivityComponent.cpp" "BaseCombatAIComponent.cpp" "BouncerComponent.cpp" diff --git a/dGame/dComponents/VendorComponent.cpp b/dGame/dComponents/VendorComponent.cpp index afa3d013..9e9428f7 100644 --- a/dGame/dComponents/VendorComponent.cpp +++ b/dGame/dComponents/VendorComponent.cpp @@ -8,6 +8,11 @@ #include "CDLootMatrixTable.h" #include "CDLootTableTable.h" #include "CDItemComponentTable.h" +#include "InventoryComponent.h" +#include "Character.h" +#include "eVendorTransactionResult.h" +#include "UserManager.h" +#include "CheatDetection.h" VendorComponent::VendorComponent(Entity* parent) : Component(parent) { m_HasStandardCostItems = false; @@ -151,3 +156,60 @@ void VendorComponent::HandleMrReeCameras(){ m_Inventory.push_back(SoldItem(camera, 0)); } } + + +void VendorComponent::Buy(Entity* buyer, LOT lot, uint32_t count) { + + if (!SellsItem(lot)) { + auto* user = UserManager::Instance()->GetUser(buyer->GetSystemAddress()); + CheatDetection::ReportCheat(user, buyer->GetSystemAddress(), "Attempted to buy item %i from achievement vendor %i that is not purchasable", lot, m_Parent->GetLOT()); + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL); + return; + } + + auto* inventoryComponent = buyer->GetComponent(); + if (!inventoryComponent) { + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL); + return; + } + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); + int itemCompID = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::ITEM); + CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); + + // Extra currency that needs to be deducted in case of crafting + auto craftingCurrencies = CDItemComponentTable::ParseCraftingCurrencies(itemComp); + for (const auto& [crafintCurrencyLOT, crafintCurrencyCount]: craftingCurrencies) { + if (inventoryComponent->GetLotCount(crafintCurrencyLOT) < (crafintCurrencyCount * count)) { + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL); + return; + } + } + for (const auto& [crafintCurrencyLOT, crafintCurrencyCount]: craftingCurrencies) { + inventoryComponent->RemoveItem(crafintCurrencyLOT, crafintCurrencyCount * count); + } + + + float buyScalar = GetBuyScalar(); + const auto coinCost = static_cast(std::floor((itemComp.baseValue * buyScalar) * count)); + + Character* character = buyer->GetCharacter(); + if (!character || character->GetCoins() < coinCost) { + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL); + return; + } + + if (Inventory::IsValidItem(itemComp.currencyLOT)) { + const uint32_t altCurrencyCost = std::floor(itemComp.altCurrencyCost * buyScalar) * count; + if (inventoryComponent->GetLotCount(itemComp.currencyLOT) < altCurrencyCost) { + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL); + return; + } + inventoryComponent->RemoveItem(itemComp.currencyLOT, altCurrencyCost); + } + + character->SetCoins(character->GetCoins() - (coinCost), eLootSourceType::VENDOR); + inventoryComponent->AddItem(lot, count, eLootSourceType::VENDOR); + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_SUCCESS); + +} \ No newline at end of file diff --git a/dGame/dComponents/VendorComponent.h b/dGame/dComponents/VendorComponent.h index 48b766d2..9025148b 100644 --- a/dGame/dComponents/VendorComponent.h +++ b/dGame/dComponents/VendorComponent.h @@ -47,6 +47,7 @@ public: m_DirtyVendor = true; } + void Buy(Entity* buyer, LOT lot, uint32_t count); private: void SetupMaxCustomVendor(); diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index c38ef880..a62bf382 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -78,6 +78,7 @@ #include "LevelProgressionComponent.h" #include "DonationVendorComponent.h" #include "GhostComponent.h" +#include "AchievementVendorComponent.h" // Message includes: #include "dZoneManager.h" @@ -97,6 +98,7 @@ #include "ePetAbilityType.h" #include "ActivityManager.h" #include "PlayerManager.h" +#include "eVendorTransactionResult.h" #include "CDComponentsRegistryTable.h" #include "CDObjectsTable.h" @@ -1323,15 +1325,14 @@ void GameMessages::SendVendorStatusUpdate(Entity* entity, const SystemAddress& s SEND_PACKET; } -void GameMessages::SendVendorTransactionResult(Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::SendVendorTransactionResult(Entity* entity, const SystemAddress& sysAddr, eVendorTransactionResult result) { CBITSTREAM; CMSGHEADER; - int iResult = 0x02; // success, seems to be the only relevant one bitStream.Write(entity->GetObjectID()); bitStream.Write(eGameMessageType::VENDOR_TRANSACTION_RESULT); - bitStream.Write(iResult); + bitStream.Write(result); SEND_PACKET; } @@ -4664,94 +4665,27 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti if (!user) return; Entity* player = Game::entityManager->GetEntity(user->GetLoggedInChar()); if (!player) return; + + // handle buying normal items + auto* vendorComponent = entity->GetComponent(); + if (vendorComponent) { + vendorComponent->Buy(player, item, count); + return; + } - auto* propertyVendorComponent = static_cast(entity->GetComponent(eReplicaComponentType::PROPERTY_VENDOR)); + // handle buying achievement items + auto* achievementVendorComponent = entity->GetComponent(); + if (achievementVendorComponent) { + achievementVendorComponent->Buy(player, item, count); + return; + } - if (propertyVendorComponent != nullptr) { + // Handle buying properties + auto* propertyVendorComponent = entity->GetComponent(); + if (propertyVendorComponent) { propertyVendorComponent->OnBuyFromVendor(player, bConfirmed, item, count); - return; } - - const auto isCommendationVendor = entity->GetLOT() == 13806; - - auto* vend = entity->GetComponent(); - if (!vend && !isCommendationVendor) return; - - auto* inv = player->GetComponent(); - if (!inv) return; - - if (!isCommendationVendor && !vend->SellsItem(item)) { - LOG("User %llu %s tried to buy an item %i from a vendor when they do not sell said item", player->GetObjectID(), user->GetUsername().c_str(), item); - return; - } - - CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); - - int itemCompID = compRegistryTable->GetByIDAndType(item, eReplicaComponentType::ITEM); - CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); - - Character* character = player->GetCharacter(); - if (!character) return; - - // Extra currency that needs to be deducted in case of crafting - auto craftingCurrencies = CDItemComponentTable::ParseCraftingCurrencies(itemComp); - for (const auto& craftingCurrency : craftingCurrencies) { - inv->RemoveItem(craftingCurrency.first, craftingCurrency.second * count); - } - - if (isCommendationVendor) { - if (itemComp.commendationLOT != 13763) { - return; - } - - auto* missionComponent = player->GetComponent(); - - if (missionComponent == nullptr) { - return; - } - - LOT tokenId = -1; - - if (missionComponent->GetMissionState(545) == eMissionState::COMPLETE) tokenId = 8318; // "Assembly Token" - if (missionComponent->GetMissionState(556) == eMissionState::COMPLETE) tokenId = 8321; // "Venture League Token" - if (missionComponent->GetMissionState(567) == eMissionState::COMPLETE) tokenId = 8319; // "Sentinels Token" - if (missionComponent->GetMissionState(578) == eMissionState::COMPLETE) tokenId = 8320; // "Paradox Token" - - const uint32_t altCurrencyCost = itemComp.commendationCost * count; - - if (inv->GetLotCount(tokenId) < altCurrencyCost) { - return; - } - - inv->RemoveItem(tokenId, altCurrencyCost); - - inv->AddItem(item, count, eLootSourceType::VENDOR); - } else { - float buyScalar = vend->GetBuyScalar(); - - const auto coinCost = static_cast(std::floor((itemComp.baseValue * buyScalar) * count)); - - if (character->GetCoins() < coinCost) { - return; - } - - if (Inventory::IsValidItem(itemComp.currencyLOT)) { - const uint32_t altCurrencyCost = std::floor(itemComp.altCurrencyCost * buyScalar) * count; - - if (inv->GetLotCount(itemComp.currencyLOT) < altCurrencyCost) { - return; - } - - inv->RemoveItem(itemComp.currencyLOT, altCurrencyCost); - } - - character->SetCoins(character->GetCoins() - (coinCost), eLootSourceType::VENDOR); - inv->AddItem(item, count, eLootSourceType::VENDOR); - } - - GameMessages::SendVendorTransactionResult(entity, sysAddr); } void GameMessages::HandleSellToVendor(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { @@ -4785,7 +4719,10 @@ void GameMessages::HandleSellToVendor(RakNet::BitStream* inStream, Entity* entit CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); // Items with a base value of 0 or max int are special items that should not be sold if they're not sub items - if (itemComp.baseValue == 0 || itemComp.baseValue == UINT_MAX) return; + if (itemComp.baseValue == 0 || itemComp.baseValue == UINT_MAX) { + GameMessages::SendVendorTransactionResult(entity, sysAddr, eVendorTransactionResult::SELL_FAIL); + return; + } float sellScalar = vend->GetSellScalar(); if (Inventory::IsValidItem(itemComp.currencyLOT)) { @@ -4793,11 +4730,9 @@ void GameMessages::HandleSellToVendor(RakNet::BitStream* inStream, Entity* entit inv->AddItem(itemComp.currencyLOT, std::floor(altCurrency), eLootSourceType::VENDOR); // Return alt currencies like faction tokens. } - //inv->RemoveItem(count, -1, iObjID); inv->MoveItemToInventory(item, eInventoryType::VENDOR_BUYBACK, count, true, false, true); character->SetCoins(std::floor(character->GetCoins() + (static_cast(itemComp.baseValue * sellScalar) * count)), eLootSourceType::VENDOR); - //Game::entityManager->SerializeEntity(player); // so inventory updates - GameMessages::SendVendorTransactionResult(entity, sysAddr); + GameMessages::SendVendorTransactionResult(entity, sysAddr, eVendorTransactionResult::SELL_SUCCESS); } void GameMessages::HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { @@ -4839,16 +4774,16 @@ void GameMessages::HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* const auto cost = static_cast(std::floor(((itemComp.baseValue * sellScalar) * count))); if (character->GetCoins() < cost) { + GameMessages::SendVendorTransactionResult(entity, sysAddr, eVendorTransactionResult::PURCHASE_FAIL); return; } if (Inventory::IsValidItem(itemComp.currencyLOT)) { const uint32_t altCurrencyCost = std::floor(itemComp.altCurrencyCost * sellScalar) * count; - if (inv->GetLotCount(itemComp.currencyLOT) < altCurrencyCost) { + GameMessages::SendVendorTransactionResult(entity, sysAddr, eVendorTransactionResult::PURCHASE_FAIL); return; } - inv->RemoveItem(itemComp.currencyLOT, altCurrencyCost); } @@ -4856,7 +4791,7 @@ void GameMessages::HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* inv->MoveItemToInventory(item, Inventory::FindInventoryTypeForLot(item->GetLot()), count, true, false); character->SetCoins(character->GetCoins() - cost, eLootSourceType::VENDOR); //Game::entityManager->SerializeEntity(player); // so inventory updates - GameMessages::SendVendorTransactionResult(entity, sysAddr); + GameMessages::SendVendorTransactionResult(entity, sysAddr, eVendorTransactionResult::PURCHASE_SUCCESS); } void GameMessages::HandleParseChatMessage(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index a96bbf60..9604d261 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -38,6 +38,7 @@ enum class eUseItemResponse : uint32_t; enum class eQuickBuildFailReason : uint32_t; enum class eQuickBuildState : uint32_t; enum class BehaviorSlot : int32_t; +enum class eVendorTransactionResult : uint32_t; namespace GameMessages { class PropertyDataMessage; @@ -135,7 +136,7 @@ namespace GameMessages { void SendVendorOpenWindow(Entity* entity, const SystemAddress& sysAddr); void SendVendorStatusUpdate(Entity* entity, const SystemAddress& sysAddr, bool bUpdateOnly = false); - void SendVendorTransactionResult(Entity* entity, const SystemAddress& sysAddr); + void SendVendorTransactionResult(Entity* entity, const SystemAddress& sysAddr, eVendorTransactionResult result); void SendRemoveItemFromInventory(Entity* entity, const SystemAddress& sysAddr, LWOOBJID iObjID, LOT templateID, int inventoryType, uint32_t stackCount, uint32_t stackRemaining); void SendConsumeClientItem(Entity* entity, bool bSuccess, LWOOBJID item); diff --git a/dNet/AuthPackets.cpp b/dNet/AuthPackets.cpp index 25ccc902..54c28299 100644 --- a/dNet/AuthPackets.cpp +++ b/dNet/AuthPackets.cpp @@ -82,7 +82,7 @@ void AuthPackets::SendHandshake(dServer* server, const SystemAddress& sysAddr, c if (serverType == ServerType::Auth) bitStream.Write(ServiceId::Auth); else if (serverType == ServerType::World) bitStream.Write(ServiceId::World); else bitStream.Write(ServiceId::General); - bitStream.Write(774909490); + bitStream.Write(215523405360); server->Send(&bitStream, sysAddr, false); } From cf706d4974199c053addb708525195081d3b711f Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 25 Feb 2024 05:56:01 -0800 Subject: [PATCH 29/50] Remove ag special case patch (#1462) Tested that revision was never the poison value in any lvl file when starting zone 1100. --- dZoneManager/Level.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/dZoneManager/Level.cpp b/dZoneManager/Level.cpp index 9524d908..5f35b629 100644 --- a/dZoneManager/Level.cpp +++ b/dZoneManager/Level.cpp @@ -200,9 +200,6 @@ void Level::ReadFileInfoChunk(std::istream& file, Header& header) { BinaryIO::BinaryRead(file, header.fileInfo.enviromentChunkStart); BinaryIO::BinaryRead(file, header.fileInfo.objectChunkStart); BinaryIO::BinaryRead(file, header.fileInfo.particleChunkStart); - - //PATCH FOR AG: (messed up file?) - if (header.fileInfo.revision == 0xCDCDCDCD && m_ParentZone->GetZoneID().GetMapID() == 1100) header.fileInfo.revision = 26; } void Level::ReadSceneObjectDataChunk(std::istream& file, Header& header) { From 192c8cf974b46b03b5604457274797733a73d330 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Sun, 25 Feb 2024 16:59:10 -0600 Subject: [PATCH 30/50] feat: refactor vanity (#1477) * feat: refactor vanity cleanup code to be generalized for objects remove unused party feature add fallback to data to text Allow for better organizing data in multiple files remove special case flag values in favor of config data general cleanup and fixes * newline at eof's --- CMakeLists.txt | 2 +- dGame/Entity.cpp | 6 + dGame/Entity.h | 2 + dGame/dUtilities/VanityUtilities.cpp | 559 +++++++----------- dGame/dUtilities/VanityUtilities.h | 43 +- dScripts/02_server/DLU/CMakeLists.txt | 2 +- ...NPC.cpp => DLUVanityTeleportingObject.cpp} | 26 +- ...nityNPC.h => DLUVanityTeleportingObject.h} | 7 +- dScripts/CppScripts.cpp | 6 +- vanity/atm.xml | 23 + vanity/{NPC.xml => dev-tribute.xml} | 345 +++++------ vanity/root.xml | 4 + 12 files changed, 414 insertions(+), 611 deletions(-) rename dScripts/02_server/DLU/{DLUVanityNPC.cpp => DLUVanityTeleportingObject.cpp} (51%) rename dScripts/02_server/DLU/{DLUVanityNPC.h => DLUVanityTeleportingObject.h} (54%) create mode 100644 vanity/atm.xml rename vanity/{NPC.xml => dev-tribute.xml} (65%) create mode 100644 vanity/root.xml diff --git a/CMakeLists.txt b/CMakeLists.txt index e085bfe7..b36bdb29 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -179,7 +179,7 @@ file(ARCHIVE_EXTRACT INPUT ${PROJECT_BINARY_DIR}/navmeshes.zip DESTINATION ${PRO file(REMOVE ${PROJECT_BINARY_DIR}/navmeshes.zip) # Copy vanity files on first build -set(VANITY_FILES "CREDITS.md" "INFO.md" "TESTAMENT.md" "NPC.xml") +set(VANITY_FILES "CREDITS.md" "INFO.md" "TESTAMENT.md" "root.xml" "dev-tribute.xml" "atm.xml") foreach(file ${VANITY_FILES}) configure_file("${CMAKE_SOURCE_DIR}/vanity/${file}" "${CMAKE_BINARY_DIR}/vanity/${file}" COPYONLY) diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index bb932991..dd15f69d 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -2197,3 +2197,9 @@ void Entity::SetRespawnRot(const NiQuaternion& rotation) { auto* characterComponent = GetComponent(); if (characterComponent) characterComponent->SetRespawnRot(rotation); } + +void Entity::SetScale(const float scale) { + if (scale == m_Scale) return; + m_Scale = scale; + Game::entityManager->SerializeEntity(this); +} \ No newline at end of file diff --git a/dGame/Entity.h b/dGame/Entity.h index 6546e458..7d5e24c9 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -295,6 +295,8 @@ public: void ProcessPositionUpdate(PositionUpdate& update); + void SetScale(const float scale); + protected: LWOOBJID m_ObjectID; diff --git a/dGame/dUtilities/VanityUtilities.cpp b/dGame/dUtilities/VanityUtilities.cpp index fa1a3eac..3e93f830 100644 --- a/dGame/dUtilities/VanityUtilities.cpp +++ b/dGame/dUtilities/VanityUtilities.cpp @@ -22,143 +22,13 @@ #include -std::vector VanityUtilities::m_NPCs = {}; -std::vector VanityUtilities::m_Parties = {}; -std::vector VanityUtilities::m_PartyPhrases = {}; +std::vector VanityUtilities::m_Objects = {}; +std::set VanityUtilities::m_LoadedFiles = {}; + void VanityUtilities::SpawnVanity() { - if (Game::config->GetValue("disable_vanity") == "1") { - return; - } - const uint32_t zoneID = Game::server->GetZoneID(); - for (const auto& npc : m_NPCs) { - if (npc.m_ID == LWOOBJID_EMPTY) continue; - if (npc.m_LOT == 176){ - Game::zoneManager->RemoveSpawner(npc.m_ID); - } else{ - auto* entity = Game::entityManager->GetEntity(npc.m_ID); - if (!entity) continue; - entity->Smash(LWOOBJID_EMPTY, eKillType::VIOLENT); - } - } - - m_NPCs.clear(); - m_Parties.clear(); - m_PartyPhrases.clear(); - - ParseXML((BinaryPathFinder::GetBinaryDir() / "vanity/NPC.xml").string()); - - // Loop through all parties - for (const auto& party : m_Parties) { - const auto chance = party.m_Chance; - const auto zone = party.m_Zone; - - if (zone != Game::server->GetZoneID()) { - continue; - } - - float rate = GeneralUtils::GenerateRandomNumber(0, 1); - if (chance < rate) { - continue; - } - - // Copy m_NPCs into a new vector - std::vector npcList = m_NPCs; - std::vector taken = {}; - - LOG("Spawning party with %i locations", party.m_Locations.size()); - - // Loop through all locations - for (const auto& location : party.m_Locations) { - rate = GeneralUtils::GenerateRandomNumber(0, 1); - if (0.75f < rate) { - continue; - } - - // Get a random NPC - auto npcIndex = GeneralUtils::GenerateRandomNumber(0, npcList.size() - 1); - - while (std::find(taken.begin(), taken.end(), npcIndex) != taken.end()) { - npcIndex = GeneralUtils::GenerateRandomNumber(0, npcList.size() - 1); - } - - auto& npc = npcList[npcIndex]; - // Skip spawners - if (npc.m_LOT == 176) continue; - - taken.push_back(npcIndex); - - LOG("ldf size is %i", npc.ldf.size()); - if (npc.ldf.empty()) { - npc.ldf = { - new LDFData>(u"syncLDF", { u"custom_script_client" }), - new LDFData(u"custom_script_client", u"scripts\\ai\\SPEC\\MISSION_MINIGAME_CLIENT.lua") - }; - } - - // Spawn the NPC - if (npc.m_LOT == 176){ - npc.m_ID = SpawnSpawner(npc.m_LOT, location.m_Position, location.m_Rotation, npc.ldf); - } else { - auto* npcEntity = SpawnNPC(npc.m_LOT, npc.m_Name, location.m_Position, location.m_Rotation, npc.m_Equipment, npc.ldf); - if (!npc.m_Phrases.empty()) { - npcEntity->SetVar>(u"chats", m_PartyPhrases); - SetupNPCTalk(npcEntity); - } - } - } - return; - } - - // Loop through all NPCs - for (auto& npc : m_NPCs) { - if (npc.m_Locations.find(Game::server->GetZoneID()) == npc.m_Locations.end()) - continue; - - const std::vector& locations = npc.m_Locations.at(Game::server->GetZoneID()); - - // Pick a random location - const auto& location = locations[GeneralUtils::GenerateRandomNumber( - static_cast(0), static_cast(locations.size() - 1))]; - - float rate = GeneralUtils::GenerateRandomNumber(0, 1); - if (location.m_Chance < rate) { - continue; - } - - if (npc.ldf.empty()) { - npc.ldf = { - new LDFData>(u"syncLDF", { u"custom_script_client" }), - new LDFData(u"custom_script_client", u"scripts\\ai\\SPEC\\MISSION_MINIGAME_CLIENT.lua") - }; - } - if (npc.m_LOT == 176){ - npc.m_ID = SpawnSpawner(npc.m_LOT, location.m_Position, location.m_Rotation, npc.ldf); - } else { - // Spawn the NPC - auto* npcEntity = SpawnNPC(npc.m_LOT, npc.m_Name, location.m_Position, location.m_Rotation, npc.m_Equipment, npc.ldf); - if (!npcEntity) continue; - npc.m_ID = npcEntity->GetObjectID(); - if (!npc.m_Phrases.empty()){ - npcEntity->SetVar>(u"chats", npc.m_Phrases); - - auto* scriptComponent = npcEntity->GetComponent(); - - if (scriptComponent && !npc.m_Script.empty()) { - scriptComponent->SetScript(npc.m_Script); - scriptComponent->SetSerialized(false); - - for (const auto& npc : npc.m_Flags) { - npcEntity->SetVar(GeneralUtils::ASCIIToUTF16(npc.first), npc.second); - } - } - SetupNPCTalk(npcEntity); - } - } - } - if (zoneID == 1200) { { EntityInfo info; @@ -175,38 +45,99 @@ void VanityUtilities::SpawnVanity() { Game::entityManager->ConstructEntity(entity); } } + + if (Game::config->GetValue("disable_vanity") == "1") { + return; + } + + for (const auto& npc : m_Objects) { + if (npc.m_ID == LWOOBJID_EMPTY) continue; + if (npc.m_LOT == 176){ + Game::zoneManager->RemoveSpawner(npc.m_ID); + } else{ + auto* entity = Game::entityManager->GetEntity(npc.m_ID); + if (!entity) continue; + entity->Smash(LWOOBJID_EMPTY, eKillType::VIOLENT); + } + } + + m_Objects.clear(); + m_LoadedFiles.clear(); + + ParseXML((BinaryPathFinder::GetBinaryDir() / "vanity/root.xml").string()); + + // Loop through all objects + for (auto& object : m_Objects) { + if (object.m_Locations.find(Game::server->GetZoneID()) == object.m_Locations.end()) continue; + + const std::vector& locations = object.m_Locations.at(Game::server->GetZoneID()); + + // Pick a random location + const auto& location = locations[GeneralUtils::GenerateRandomNumber( + static_cast(0), static_cast(locations.size() - 1))]; + + float rate = GeneralUtils::GenerateRandomNumber(0, 1); + if (location.m_Chance < rate) continue; + + if (object.m_Config.empty()) { + object.m_Config = { + new LDFData>(u"syncLDF", { u"custom_script_client" }), + new LDFData(u"custom_script_client", u"scripts\\ai\\SPEC\\MISSION_MINIGAME_CLIENT.lua") + }; + } + if (object.m_LOT == 176){ + object.m_ID = SpawnSpawner(object, location); + } else { + // Spawn the NPC + auto* objectEntity = SpawnObject(object, location); + if (!objectEntity) continue; + object.m_ID = objectEntity->GetObjectID(); + if (!object.m_Phrases.empty()){ + objectEntity->SetVar>(u"chats", object.m_Phrases); + + auto* scriptComponent = objectEntity->GetComponent(); + + if (scriptComponent && !object.m_Script.empty()) { + scriptComponent->SetScript(object.m_Script); + scriptComponent->SetSerialized(false); + } + SetupNPCTalk(objectEntity); + } + } + } } -LWOOBJID VanityUtilities::SpawnSpawner(LOT lot, const NiPoint3& position, const NiQuaternion& rotation, const std::vector& ldf){ +LWOOBJID VanityUtilities::SpawnSpawner(const VanityObject& object, const VanityObjectLocation& location) { SceneObject obj; - obj.lot = lot; + obj.lot = object.m_LOT; // guratantee we have no collisions do { obj.id = ObjectIDManager::GenerateObjectID(); } while(Game::zoneManager->GetSpawner(obj.id)); - obj.position = position; - obj.rotation = rotation; - obj.settings = ldf; + obj.position = location.m_Position; + obj.rotation = location.m_Rotation; + obj.settings = object.m_Config; Level::MakeSpawner(obj); return obj.id; } -Entity* VanityUtilities::SpawnNPC(LOT lot, const std::string& name, const NiPoint3& position, const NiQuaternion& rotation, const std::vector& inventory, const std::vector& ldf) { +Entity* VanityUtilities::SpawnObject(const VanityObject& object, const VanityObjectLocation& location) { EntityInfo info; - info.lot = lot; - info.pos = position; - info.rot = rotation; + info.lot = object.m_LOT; + info.pos = location.m_Position; + info.rot = location.m_Rotation; + info.scale = location.m_Scale; info.spawnerID = Game::entityManager->GetZoneControlEntity()->GetObjectID(); - info.settings = ldf; + info.settings = object.m_Config; auto* entity = Game::entityManager->CreateEntity(info); - entity->SetVar(u"npcName", name); + entity->SetVar(u"npcName", object.m_Name); if (entity->GetVar(u"noGhosting")) entity->SetIsGhostingCandidate(false); auto* inventoryComponent = entity->GetComponent(); - if (inventoryComponent && !inventory.empty()) { - inventoryComponent->SetNPCItems(inventory); + if (inventoryComponent && !object.m_Equipment.empty()) { + inventoryComponent->SetNPCItems(object.m_Equipment); } auto* destroyableComponent = entity->GetComponent(); @@ -223,6 +154,11 @@ Entity* VanityUtilities::SpawnNPC(LOT lot, const std::string& name, const NiPoin } void VanityUtilities::ParseXML(const std::string& file) { + if (m_LoadedFiles.contains(file)){ + LOG("Trying to load vanity file %s twice!!!", file.c_str()); + return; + } + m_LoadedFiles.insert(file); // Read the entire file std::ifstream xmlFile(file); std::string xml((std::istreambuf_iterator(xmlFile)), std::istreambuf_iterator()); @@ -231,210 +167,112 @@ void VanityUtilities::ParseXML(const std::string& file) { tinyxml2::XMLDocument doc; doc.Parse(xml.c_str(), xml.size()); - // Read the NPCs - auto* npcs = doc.FirstChildElement("npcs"); - - if (npcs == nullptr) { - LOG("Failed to parse NPCs"); - return; - } - - for (auto* party = npcs->FirstChildElement("party"); party != nullptr; party = party->NextSiblingElement("party")) { - // Get 'zone' as uint32_t and 'chance' as float - uint32_t zone = 0; - float chance = 0.0f; - - if (party->Attribute("zone") != nullptr) { - zone = std::stoul(party->Attribute("zone")); - } - - if (party->Attribute("chance") != nullptr) { - chance = std::stof(party->Attribute("chance")); - } - - VanityParty partyInfo; - partyInfo.m_Zone = zone; - partyInfo.m_Chance = chance; - - auto* locations = party->FirstChildElement("locations"); - - if (locations == nullptr) { - LOG("Failed to parse party locations"); - continue; - } - - for (auto* location = locations->FirstChildElement("location"); location != nullptr; - location = location->NextSiblingElement("location")) { - // Get the location data - auto* x = location->Attribute("x"); - auto* y = location->Attribute("y"); - auto* z = location->Attribute("z"); - auto* rw = location->Attribute("rw"); - auto* rx = location->Attribute("rx"); - auto* ry = location->Attribute("ry"); - auto* rz = location->Attribute("rz"); - - if (x == nullptr || y == nullptr || z == nullptr || rw == nullptr || rx == nullptr || ry == nullptr - || rz == nullptr) { - LOG("Failed to parse party location data"); + // Read the objects + auto* files = doc.FirstChildElement("files"); + if (files) { + for (auto* file = files->FirstChildElement("file"); file != nullptr; file = file->NextSiblingElement("file")) { + std::string enabled = file->Attribute("enabled"); + std::string filename = file->Attribute("name"); + if (enabled != "1") { continue; } - - VanityNPCLocation locationData; - locationData.m_Position = { std::stof(x), std::stof(y), std::stof(z) }; - locationData.m_Rotation = { std::stof(rw), std::stof(rx), std::stof(ry), std::stof(rz) }; - locationData.m_Chance = 1.0f; - - partyInfo.m_Locations.push_back(locationData); - } - - m_Parties.push_back(partyInfo); - } - - auto* partyPhrases = npcs->FirstChildElement("partyphrases"); - - if (partyPhrases == nullptr) { - LOG("No party phrases found"); - } else { - for (auto* phrase = partyPhrases->FirstChildElement("phrase"); phrase != nullptr; - phrase = phrase->NextSiblingElement("phrase")) { - // Get the phrase - auto* text = phrase->GetText(); - - if (text == nullptr) { - LOG("Failed to parse party phrase"); - continue; - } - - m_PartyPhrases.push_back(text); + ParseXML((BinaryPathFinder::GetBinaryDir() / "vanity" / filename).string()); } } - for (auto* npc = npcs->FirstChildElement("npc"); npc != nullptr; npc = npc->NextSiblingElement("npc")) { - // Get the NPC name - auto* name = npc->Attribute("name"); + // Read the objects + auto* objects = doc.FirstChildElement("objects"); - if (!name) name = ""; + if (objects) { + for (auto* object = objects->FirstChildElement("object"); object != nullptr; object = object->NextSiblingElement("object")) { + // Get the NPC name + auto* name = object->Attribute("name"); - // Get the NPC lot - auto* lot = npc->Attribute("lot"); + if (!name) name = ""; - if (lot == nullptr) { - LOG("Failed to parse NPC lot"); - continue; - } + // Get the NPC lot + auto* lot = object->Attribute("lot"); - // Get the equipment - auto* equipment = npc->FirstChildElement("equipment"); - std::vector inventory; - - if (equipment) { - auto* text = equipment->GetText(); - - if (text != nullptr) { - std::string equipmentString(text); - - std::vector splitEquipment = GeneralUtils::SplitString(equipmentString, ','); - - for (auto& item : splitEquipment) { - inventory.push_back(std::stoi(item)); - } - } - } - - - // Get the phrases - auto* phrases = npc->FirstChildElement("phrases"); - - std::vector phraseList = {}; - - if (phrases) { - for (auto* phrase = phrases->FirstChildElement("phrase"); phrase != nullptr; - phrase = phrase->NextSiblingElement("phrase")) { - // Get the phrase - auto* text = phrase->GetText(); - if (text == nullptr) { - LOG("Failed to parse NPC phrase"); - continue; - } - phraseList.push_back(text); - } - } - - // Get the script - auto* scriptElement = npc->FirstChildElement("script"); - - std::string scriptName = ""; - - if (scriptElement != nullptr) { - auto* scriptNameAttribute = scriptElement->Attribute("name"); - if (scriptNameAttribute) scriptName = scriptNameAttribute; - } - - auto* ldfElement = npc->FirstChildElement("ldf"); - std::vector keys = {}; - - std::vector ldf = {}; - if(ldfElement) { - for (auto* entry = ldfElement->FirstChildElement("entry"); entry != nullptr; - entry = entry->NextSiblingElement("entry")) { - // Get the ldf data - auto* data = entry->Attribute("data"); - if (!data) continue; - - LDFBaseData* ldfData = LDFBaseData::DataFromString(data); - keys.push_back(ldfData->GetKey()); - ldf.push_back(ldfData); - } - } - if (!keys.empty()) ldf.push_back(new LDFData>(u"syncLDF", keys)); - - VanityNPC npcData; - npcData.m_Name = name; - npcData.m_LOT = std::stoi(lot); - npcData.m_Equipment = inventory; - npcData.m_Phrases = phraseList; - npcData.m_Script = scriptName; - npcData.ldf = ldf; - - // Get flags - auto* flags = npc->FirstChildElement("flags"); - - if (flags != nullptr) { - for (auto* flag = flags->FirstChildElement("flag"); flag != nullptr; - flag = flag->NextSiblingElement("flag")) { - // Get the flag name - auto* name = flag->Attribute("name"); - - if (name == nullptr) { - LOG("Failed to parse NPC flag name"); - continue; - } - - // Get the flag value - auto* value = flag->Attribute("value"); - - if (value == nullptr) { - LOG("Failed to parse NPC flag value"); - continue; - } - - npcData.m_Flags[name] = std::stoi(value); - } - } - - // Get the zones - for (auto* zone = npc->FirstChildElement("zone"); zone != nullptr; zone = zone->NextSiblingElement("zone")) { - // Get the zone ID - auto* zoneID = zone->Attribute("id"); - - if (zoneID == nullptr) { - LOG("Failed to parse NPC zone ID"); + if (lot == nullptr) { + LOG("Failed to parse object lot"); continue; } + // Get the equipment + auto* equipment = object->FirstChildElement("equipment"); + std::vector inventory; + + if (equipment) { + auto* text = equipment->GetText(); + + if (text != nullptr) { + std::string equipmentString(text); + + std::vector splitEquipment = GeneralUtils::SplitString(equipmentString, ','); + + for (auto& item : splitEquipment) { + inventory.push_back(std::stoi(item)); + } + } + } + + + // Get the phrases + auto* phrases = object->FirstChildElement("phrases"); + + std::vector phraseList = {}; + + if (phrases) { + for (auto* phrase = phrases->FirstChildElement("phrase"); phrase != nullptr; + phrase = phrase->NextSiblingElement("phrase")) { + // Get the phrase + auto* text = phrase->GetText(); + if (text == nullptr) { + LOG("Failed to parse NPC phrase"); + continue; + } + phraseList.push_back(text); + } + } + + // Get the script + auto* scriptElement = object->FirstChildElement("script"); + + std::string scriptName = ""; + + if (scriptElement != nullptr) { + auto* scriptNameAttribute = scriptElement->Attribute("name"); + if (scriptNameAttribute) scriptName = scriptNameAttribute; + } + + auto* configElement = object->FirstChildElement("config"); + std::vector keys = {}; + + std::vector config = {}; + if(configElement) { + for (auto* key = configElement->FirstChildElement("key"); key != nullptr; + key = key->NextSiblingElement("key")) { + // Get the config data + auto* data = key->Attribute("data"); + if (!data) continue; + + LDFBaseData* configData = LDFBaseData::DataFromString(data); + keys.push_back(configData->GetKey()); + config.push_back(configData); + } + } + if (!keys.empty()) config.push_back(new LDFData>(u"syncLDF", keys)); + + VanityObject objectData; + objectData.m_Name = name; + objectData.m_LOT = std::stoi(lot); + objectData.m_Equipment = inventory; + objectData.m_Phrases = phraseList; + objectData.m_Script = scriptName; + objectData.m_Config = config; + // Get the locations - auto* locations = zone->FirstChildElement("locations"); + auto* locations = object->FirstChildElement("locations"); if (locations == nullptr) { LOG("Failed to parse NPC locations"); @@ -443,7 +281,9 @@ void VanityUtilities::ParseXML(const std::string& file) { for (auto* location = locations->FirstChildElement("location"); location != nullptr; location = location->NextSiblingElement("location")) { + // Get the location data + auto* zoneID = location->Attribute("zone"); auto* x = location->Attribute("x"); auto* y = location->Attribute("y"); auto* z = location->Attribute("z"); @@ -452,41 +292,52 @@ void VanityUtilities::ParseXML(const std::string& file) { auto* ry = location->Attribute("ry"); auto* rz = location->Attribute("rz"); - if (x == nullptr || y == nullptr || z == nullptr || rw == nullptr || rx == nullptr || ry == nullptr + if (zoneID == nullptr || x == nullptr || y == nullptr || z == nullptr || rw == nullptr || rx == nullptr || ry == nullptr || rz == nullptr) { LOG("Failed to parse NPC location data"); continue; } - VanityNPCLocation locationData; + VanityObjectLocation locationData; locationData.m_Position = { std::stof(x), std::stof(y), std::stof(z) }; locationData.m_Rotation = { std::stof(rw), std::stof(rx), std::stof(ry), std::stof(rz) }; locationData.m_Chance = 1.0f; - if (location->Attribute("chance") != nullptr) { + if (location->Attribute("chance")) { locationData.m_Chance = std::stof(location->Attribute("chance")); } - const auto& it = npcData.m_Locations.find(std::stoi(zoneID)); + if (location->Attribute("scale")) { + locationData.m_Scale = std::stof(location->Attribute("scale")); + } - if (it != npcData.m_Locations.end()) { + + const auto& it = objectData.m_Locations.find(std::stoi(zoneID)); + + if (it != objectData.m_Locations.end()) { it->second.push_back(locationData); } else { - std::vector locations; + std::vector locations; locations.push_back(locationData); - npcData.m_Locations.insert(std::make_pair(std::stoi(zoneID), locations)); + objectData.m_Locations.insert(std::make_pair(std::stoi(zoneID), locations)); + } + + if (!(std::find(keys.begin(), keys.end(), u"teleport") != keys.end())) { + m_Objects.push_back(objectData); + objectData.m_Locations.clear(); } } + if (std::find(keys.begin(), keys.end(), u"teleport") != keys.end()) { + m_Objects.push_back(objectData); + } } - - m_NPCs.push_back(npcData); } } -VanityNPC* VanityUtilities::GetNPC(const std::string& name) { - for (size_t i = 0; i < m_NPCs.size(); i++) { - if (m_NPCs[i].m_Name == name) { - return &m_NPCs[i]; +VanityObject* VanityUtilities::GetObject(const std::string& name) { + for (size_t i = 0; i < m_Objects.size(); i++) { + if (m_Objects[i].m_Name == name) { + return &m_Objects[i]; } } @@ -498,10 +349,13 @@ std::string VanityUtilities::ParseMarkdown(const std::string& file) { // Read the file into a string std::ifstream t(file); - + std::stringstream output; // If the file does not exist, return an empty string. if (!t.good()) { - return ""; + output << "File "; + output << file.substr(file.rfind("/") + 1); + output << " not found!\nContact your DarkflameServer admin\nor find the server source at https://github.com/DarkflameUniverse/DarkflameServer"; + return output.str(); } std::stringstream buffer; @@ -511,7 +365,6 @@ std::string VanityUtilities::ParseMarkdown(const std::string& file) { // Loop through all lines in the file. // Replace all instances of the markdown syntax with the corresponding HTML. // Only care about headers - std::stringstream output; std::string line; std::stringstream ss; ss << fileContents; diff --git a/dGame/dUtilities/VanityUtilities.h b/dGame/dUtilities/VanityUtilities.h index cff73bce..49bd23ab 100644 --- a/dGame/dUtilities/VanityUtilities.h +++ b/dGame/dUtilities/VanityUtilities.h @@ -3,15 +3,17 @@ #include "dCommonVars.h" #include "Entity.h" #include +#include -struct VanityNPCLocation +struct VanityObjectLocation { float m_Chance = 1.0f; NiPoint3 m_Position; NiQuaternion m_Rotation; + float m_Scale = 1.0f; }; -struct VanityNPC +struct VanityObject { LWOOBJID m_ID = LWOOBJID_EMPTY; std::string m_Name; @@ -19,37 +21,24 @@ struct VanityNPC std::vector m_Equipment; std::vector m_Phrases; std::string m_Script; - std::map m_Flags; - std::map> m_Locations; - std::vector ldf; + std::map> m_Locations; + std::vector m_Config; }; -struct VanityParty -{ - uint32_t m_Zone; - float m_Chance = 1.0f; - std::vector m_Locations; -}; class VanityUtilities { public: static void SpawnVanity(); - static Entity* SpawnNPC( - LOT lot, - const std::string& name, - const NiPoint3& position, - const NiQuaternion& rotation, - const std::vector& inventory, - const std::vector& ldf + static Entity* SpawnObject( + const VanityObject& object, + const VanityObjectLocation& location ); static LWOOBJID SpawnSpawner( - LOT lot, - const NiPoint3& position, - const NiQuaternion& rotation, - const std::vector& ldf + const VanityObject& object, + const VanityObjectLocation& location ); static std::string ParseMarkdown( @@ -60,16 +49,14 @@ public: const std::string& file ); - static VanityNPC* GetNPC(const std::string& name); + static VanityObject* GetObject(const std::string& name); private: static void SetupNPCTalk(Entity* npc); static void NPCTalk(Entity* npc); - static std::vector m_NPCs; - - static std::vector m_Parties; - - static std::vector m_PartyPhrases; + static std::vector m_Objects; + + static std::set m_LoadedFiles; }; diff --git a/dScripts/02_server/DLU/CMakeLists.txt b/dScripts/02_server/DLU/CMakeLists.txt index 64d4cbbd..fb257d3e 100644 --- a/dScripts/02_server/DLU/CMakeLists.txt +++ b/dScripts/02_server/DLU/CMakeLists.txt @@ -1,3 +1,3 @@ set(DSCRIPTS_SOURCES_02_SERVER_DLU - "DLUVanityNPC.cpp" + "DLUVanityTeleportingObject.cpp" PARENT_SCOPE) diff --git a/dScripts/02_server/DLU/DLUVanityNPC.cpp b/dScripts/02_server/DLU/DLUVanityTeleportingObject.cpp similarity index 51% rename from dScripts/02_server/DLU/DLUVanityNPC.cpp rename to dScripts/02_server/DLU/DLUVanityTeleportingObject.cpp index ba2c6604..8aff1995 100644 --- a/dScripts/02_server/DLU/DLUVanityNPC.cpp +++ b/dScripts/02_server/DLU/DLUVanityTeleportingObject.cpp @@ -1,22 +1,22 @@ -#include "DLUVanityNPC.h" +#include "DLUVanityTeleportingObject.h" #include "GameMessages.h" #include "dServer.h" #include "VanityUtilities.h" #include "RenderComponent.h" -void DLUVanityNPC::OnStartup(Entity* self) { - m_NPC = VanityUtilities::GetNPC("averysumner - Destroyer of Worlds"); +void DLUVanityTeleportingObject::OnStartup(Entity* self) { + if (!self->HasVar(u"npcName") || !self->HasVar(u"teleport")) return; + m_Object = VanityUtilities::GetObject(self->GetVarAsString(u"npcName")); - if (m_NPC == nullptr) { - return; - } + if (!m_Object) return; + if (self->HasVar(u"teleportInterval")) m_TeleportInterval = self->GetVar(u"teleportInterval"); if (self->GetVar(u"teleport")) { - self->AddTimer("setupTeleport", 15.0f); + self->AddTimer("setupTeleport", m_TeleportInterval); } } -void DLUVanityNPC::OnTimerDone(Entity* self, std::string timerName) { +void DLUVanityTeleportingObject::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "setupTeleport") { RenderComponent::PlayAnimation(self, u"interact"); GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportBeam", "teleportBeam"); @@ -28,20 +28,22 @@ void DLUVanityNPC::OnTimerDone(Entity* self, std::string timerName) { GameMessages::SendStopFXEffect(self, true, "teleportBeam"); GameMessages::SendStopFXEffect(self, true, "teleportRings"); } else if (timerName == "teleport") { - std::vector& locations = m_NPC->m_Locations[Game::server->GetZoneID()]; + std::vector& locations = m_Object->m_Locations[Game::server->GetZoneID()]; selectLocation: - VanityNPCLocation& newLocation = locations[GeneralUtils::GenerateRandomNumber(0, locations.size() - 1)]; + VanityObjectLocation& newLocation = locations[GeneralUtils::GenerateRandomNumber(0, locations.size() - 1)]; + // try to get not the same position, but if we get the same one twice, it's fine if (self->GetPosition() == newLocation.m_Position) { - goto selectLocation; // cry about it + VanityObjectLocation& newLocation = locations[GeneralUtils::GenerateRandomNumber(0, locations.size() - 1)]; } self->SetPosition(newLocation.m_Position); self->SetRotation(newLocation.m_Rotation); + self->SetScale(newLocation.m_Scale); GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportBeam", "teleportBeam"); GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportRings", "teleportRings"); self->AddTimer("stopFX", 2.0f); - self->AddTimer("setupTeleport", 15.0f); + self->AddTimer("setupTeleport", m_TeleportInterval); } } diff --git a/dScripts/02_server/DLU/DLUVanityNPC.h b/dScripts/02_server/DLU/DLUVanityTeleportingObject.h similarity index 54% rename from dScripts/02_server/DLU/DLUVanityNPC.h rename to dScripts/02_server/DLU/DLUVanityTeleportingObject.h index aeb8e051..a13ba901 100644 --- a/dScripts/02_server/DLU/DLUVanityNPC.h +++ b/dScripts/02_server/DLU/DLUVanityTeleportingObject.h @@ -1,13 +1,14 @@ #pragma once #include "CppScripts.h" -class VanityNPC; -class DLUVanityNPC : public CppScripts::Script +class VanityObject; +class DLUVanityTeleportingObject : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnTimerDone(Entity* self, std::string timerName) override; private: - VanityNPC* m_NPC; + VanityObject* m_Object; + float m_TeleportInterval = 15.0f; }; diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 071bd7a3..7cb853e6 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -216,7 +216,7 @@ #include "NtNaomiBreadcrumbServer.h" // DLU Scripts -#include "DLUVanityNPC.h" +#include "DLUVanityTeleportingObject.h" // AM Scripts #include "AmConsoleTeleportServer.h" @@ -834,8 +834,8 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new NjNyaMissionitems(); //DLU: - else if (scriptName == "scripts\\02_server\\DLU\\DLUVanityNPC.lua") - script = new DLUVanityNPC(); + else if (scriptName == "scripts\\02_server\\DLU\\DLUVanityTeleportingObject.lua") + script = new DLUVanityTeleportingObject(); // Survival minigame else if (scriptName == "scripts\\02_server\\Enemy\\Survival\\L_AG_SURVIVAL_STROMBIE.lua") diff --git a/vanity/atm.xml b/vanity/atm.xml new file mode 100644 index 00000000..96ed1a2b --- /dev/null +++ b/vanity/atm.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vanity/NPC.xml b/vanity/dev-tribute.xml similarity index 65% rename from vanity/NPC.xml rename to vanity/dev-tribute.xml index 2311ab46..d20e31a6 100644 --- a/vanity/NPC.xml +++ b/vanity/dev-tribute.xml @@ -1,5 +1,5 @@ - - + + 6802, 2519, 2623, 14806 Sorry for the mess. @@ -11,39 +11,33 @@ Everything is awesome! I hope my behaviors are behaving themselves. - - - - - - - + + + + + 12947, 12949, 12962, 12963 I hope quickbulds are still working! Be careful crossing the gap! Have The Maelstrom stopped going invisible? - - - - - - - + + + + + 9950, 9944, 14102, 14092 Hello Explorer! It's great to see you made it! Have you heard about Darkflame? I've traveled across this entire system, but nothing beats the view here. - - - - - - - + + + + + cmerw[acowipaejio;fawjioefasdl;kfjm; @@ -51,20 +45,18 @@ zxnpoasdfiopwemsadf'kawpfo[ekasdf;'s *teleports behind you* -